Eric Bower
·
2025-06-06
api.js
1import { createApi, createSchema, mdw, slice } from "starfx";
2
3const emptyUser = { id: "", name: "" };
4export const [schema, initialState] = createSchema({
5 users: slice.table({ empty: emptyUser }),
6 cache: slice.table(),
7 loaders: slice.loaders(),
8});
9
10export const api = createApi();
11api.use(function* (ctx, next) {
12 yield* next();
13 console.log(`ctx [${ctx.name}]`, ctx);
14});
15api.use(mdw.api({ schema }));
16api.use(api.routes());
17api.use(mdw.fetch({ baseUrl: "https://jsonplaceholder.typicode.com" }));
18
19export const fetchUsers = api.get(
20 "/users",
21 function* (ctx, next) {
22 yield* next();
23
24 if (!ctx.json.ok) {
25 return;
26 }
27
28 const users = ctx.json.value.reduce((acc, user) => {
29 acc[user.id] = user;
30 return acc;
31 }, {});
32
33 yield* schema.update(schema.users.add(users));
34 },
35);