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