-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadapter.ts
More file actions
80 lines (72 loc) · 2.21 KB
/
Copy pathadapter.ts
File metadata and controls
80 lines (72 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import type { MutationState, QueryStateAdapter } from "@ailuracode/alpine-query";
import {
createMutationStateView,
createQueryStateView,
type MutationStateRecord,
type QueryStateRecord,
} from "@ailuracode/alpine-query";
import { type MapStore, map } from "nanostores";
function patchMapStore<TRecord extends Record<string, unknown>>(
store: MapStore<TRecord>,
patch: Partial<TRecord>
): void {
const current = store.get();
let next: TRecord | null = null;
for (const key of Object.keys(patch) as (keyof TRecord)[]) {
const value = patch[key];
if (current[key] !== value) {
next ??= { ...current };
next[key] = value as TRecord[keyof TRecord];
}
}
if (next) {
store.set(next);
}
}
/** Nanostores `map()` adapter for `@ailuracode/alpine-query`. */
export const nanostoresQueryAdapter: QueryStateAdapter = {
name: "Nanostores",
createQueryState<TData>(
initial: QueryStateRecord<TData>,
staleTime: number,
refetch: () => Promise<void>
) {
const store = map(initial);
const staleTimeRef = { current: staleTime };
const state = createQueryStateView(
() => store.get(),
() => staleTimeRef.current,
refetch
);
return {
state,
get: () => store.get(),
patch: (patch: Partial<QueryStateRecord<TData>>) => patchMapStore(store, patch),
listen: (listener: (record: QueryStateRecord<TData>) => void) =>
store.listen((record) => listener({ ...record })),
setStaleTime(next: number) {
staleTimeRef.current = next;
},
getStaleTime() {
return staleTimeRef.current;
},
};
},
createMutationState<TData, TVariables>(
handlers: Pick<MutationState<TData, TVariables>, "mutate" | "reset">
) {
const store = map<MutationStateRecord<TData>>({
data: undefined,
error: null,
status: "idle",
});
const state = createMutationStateView(() => store.get(), handlers);
return {
state,
get: () => store.get(),
patch: (patch: Partial<MutationStateRecord<TData>>) => patchMapStore(store, patch),
listen: (listener: (record: MutationStateRecord<TData>) => void) =>
store.listen((record) => listener({ ...record })),
};
},
};