-
-
Notifications
You must be signed in to change notification settings - Fork 191
/
Copy pathissue224.ts
81 lines (73 loc) · 1.8 KB
/
issue224.ts
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
import {
createStore,
computed,
Computed,
action,
Action,
thunk,
Thunk,
} from 'easy-peasy';
interface ObjectWithId {
id: string;
}
interface Nested {
save: Thunk<Nested, number>;
}
interface DataModel<DataItem extends ObjectWithId> {
data: { [key: number]: DataItem };
// 🚨 THIS BREAKS TYPESCRIPT 😭 🚨
// sortBy: 'none' | keyof DataItem;
sortBy: 'none' | string;
name: string;
ids: Computed<DataModel<DataItem>, number[]>;
fetched: Action<DataModel<DataItem>, DataItem[]>;
fetch: Thunk<DataModel<DataItem>, string>;
getItemById: Computed<
DataModel<DataItem>,
(id: string) => DataItem | undefined
>;
nested: Nested;
}
const dataModel = <Item extends ObjectWithId>(
name: string,
endpoint: () => Promise<Item[]>,
): DataModel<Item> => {
const result: DataModel<Item> = {
data: {},
sortBy: 'none',
name,
ids: computed((state) => Object.keys(state.data).map((id) => parseInt(id))),
fetched: action((state, items) => {
state.name;
items.forEach((item, idx) => {
state.data[idx] = item;
});
}),
fetch: thunk(async (actions, payload) => {
const data = await endpoint();
actions.fetched(data);
actions.nested.save(1);
}),
getItemById: computed((state) => (id: string) =>
Object.values(state.data).find((item) => item.id === id),
),
nested: {
save: thunk((actions, payload) => {
actions.save(payload + 1);
}),
},
};
return result;
};
interface Person extends ObjectWithId {
id: string;
name: string;
}
const personModel = dataModel<Person>('person', () =>
Promise.resolve([{ id: '1', name: 'bob' }]),
);
const store = createStore(personModel);
store.getActions().fetched([]);
// @ts-expect-error
store.getActions().data;
store.getActions().nested.save(1);