import { getByAccessorPath } from '../../lib/accessor_path.ts'; import { assertInInjectionContext, inject, effect } from '@angular/core'; import { SPACETIMEDB_CONNECTION } from '../connection_state.ts'; import type { ParamsType } from '../../sdk/index.ts'; import type { UntypedReducerDef } from '../../sdk/reducers.ts'; export function injectReducer( reducerDef: ReducerDef ): (...params: ParamsType) => void { assertInInjectionContext(injectReducer); const connState = inject(SPACETIMEDB_CONNECTION); const queue: ParamsType[] = []; const reducerName = reducerDef.accessorName; // flush queued calls when connection becomes active effect((onCleanup: (fn: () => void) => void) => { const state = connState(); if (!state.isActive) { return; } const connection = state.getConnection(); if (!connection) { return; } const callReducer = getByAccessorPath(connection.reducers, reducerName) as ( ...p: ParamsType ) => void; if (queue.length) { const pending = queue.splice(0); for (const params of pending) { callReducer(...params); } } onCleanup(() => { queue.splice(0); }); }); return (...params: ParamsType) => { const state = connState(); if (!state.isActive) { queue.push(params); return; } const connection = state.getConnection(); if (!connection) { queue.push(params); return; } const callReducer = getByAccessorPath(connection.reducers, reducerName) as ( ...p: ParamsType ) => void; return callReducer(...params); }; }