-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadapter.ts
More file actions
98 lines (87 loc) · 2.61 KB
/
Copy pathadapter.ts
File metadata and controls
98 lines (87 loc) · 2.61 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import type { MutationState, QueryState, QueryStateAdapter } from "@ailuracode/alpine-query";
import {
attachMutationFlags,
attachQueryFlags,
type MutationStateRecord,
type QueryStateRecord,
} from "@ailuracode/alpine-query";
import type AlpineType from "alpinejs";
type AlpineInstance = AlpineType.Alpine;
function toQueryRecord<TData>(state: QueryState<TData>): QueryStateRecord<TData> {
return {
data: state.data,
error: state.error,
status: state.status,
fetchStatus: state.fetchStatus,
dataUpdatedAt: state.dataUpdatedAt,
errorUpdatedAt: state.errorUpdatedAt,
};
}
function toMutationRecord<TData, TVariables>(
state: MutationState<TData, TVariables>
): MutationStateRecord<TData> {
return {
data: state.data,
error: state.error,
status: state.status,
};
}
/** Native Alpine.reactive adapter — no external store library. */
export function createAlpineStoreAdapter(Alpine: AlpineInstance): QueryStateAdapter {
return {
name: "Alpine.reactive",
createQueryState<TData>(
initial: QueryStateRecord<TData>,
staleTime: number,
refetch: () => Promise<void>
) {
const staleTimeRef = { current: staleTime };
const state = Alpine.reactive({
...initial,
refetch,
}) as QueryState<TData>;
attachQueryFlags(state, () => staleTimeRef.current);
return {
state,
get: () => toQueryRecord(state),
patch: (patch) => {
Object.assign(state, patch);
},
listen: (listener: (record: QueryStateRecord<TData>) => void) => {
listener(toQueryRecord(state));
return () => undefined;
},
setStaleTime(next: number) {
staleTimeRef.current = next;
},
getStaleTime() {
return staleTimeRef.current;
},
};
},
createMutationState<TData, TVariables>(
handlers: Pick<MutationState<TData, TVariables>, "mutate" | "reset">
) {
const state = Alpine.reactive({
data: undefined,
error: null,
status: "idle",
mutate: handlers.mutate,
reset: handlers.reset,
}) as MutationState<TData, TVariables>;
attachMutationFlags<TData, TVariables>(state);
return {
state,
get: () => toMutationRecord(state),
patch: (patch) => {
Object.assign(state, patch);
},
listen: (listener: (record: MutationStateRecord<TData>) => void) => {
listener(toMutationRecord(state));
return () => undefined;
},
};
},
};
}
export { createAlpineStoreAdapter as alpineStoreQueryAdapter };