Eric Bower
·
2025-06-06
schema.ts
1import { updateStore } from "./fx.js";
2import { slice } from "./slice/index.js";
3import type { FxMap, FxSchema, StoreUpdater } from "./types.js";
4
5const defaultSchema = <O>(): O =>
6 ({ cache: slice.table(), loaders: slice.loaders() }) as O;
7
8export function createSchema<
9 O extends FxMap,
10 S extends { [key in keyof O]: ReturnType<O[key]>["initialState"] },
11>(slices: O = defaultSchema<O>()): [FxSchema<S, O>, S] {
12 const db = Object.keys(slices).reduce<FxSchema<S, O>>(
13 (acc, key) => {
14 // deno-lint-ignore no-explicit-any
15 (acc as any)[key] = slices[key](key);
16 return acc;
17 },
18 {} as FxSchema<S, O>,
19 );
20
21 const initialState = Object.keys(db).reduce((acc, key) => {
22 // deno-lint-ignore no-explicit-any
23 (acc as any)[key] = db[key].initialState;
24 return acc;
25 }, {}) as S;
26
27 function* update(ups: StoreUpdater<S> | StoreUpdater<S>[]) {
28 return yield* updateStore(ups);
29 }
30
31 db.update = update;
32
33 return [db, initialState];
34}