-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
84 lines (68 loc) · 2.57 KB
/
index.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
82
83
84
type SharedFunctions = {
save: (key: string, value: string) => void;
load: (key: string) => string | undefined;
initialValues: { [key: string]: any }
};
// fremfor å lagre i array kan det lagres i object med en id
// trenger en wrapper rundt og som holder orden på neste index og verdiene
// trenger å plukke ting ut fra path
const sharedFunctions: SharedFunctions = {} as SharedFunctions;
export type WithId<T> = Partial<T> & { id: number };
export function createLocalREST(
save: SharedFunctions["save"],
load: SharedFunctions["load"],
initialValues?: { [key: string]: any[] },
overwriteStore?: boolean
) {
sharedFunctions.save = save;
sharedFunctions.load = load;
if (initialValues) {
Object.entries(initialValues).forEach(([index, value]) => {
if (overwriteStore || !load(index)) {
let currentIndex = 1
const storable = value.reduce((acc, item) => {
item.id = currentIndex
acc[currentIndex] = item
currentIndex++
return acc
}, {})
save(index, JSON.stringify({ values: storable, currentIndex }))
}
})
}
}
export type StorageWrapper<T> = {
values: { [key: number]: WithId<T> },
currentIndex: number
}
export function localRESTPost<T>(path: string, values: T[]): number[] {
const indexes = [] as number[]
const existingRaw = sharedFunctions.load(path) || `{"values":{}, "currentIndex": 1}`;
const existing = JSON.parse(existingRaw) as StorageWrapper<T>;
values.forEach(value => {
indexes.push(existing.currentIndex)
existing.values[existing.currentIndex] = { ...value, id: existing.currentIndex }
existing.currentIndex++
})
sharedFunctions.save(path, JSON.stringify(existing));
return indexes
}
export function localRESTPut<T>(path: string, value: WithId<T>) {
const existingRaw = sharedFunctions.load(path) || `{"values":{}, "currentIndex": 1}`;
const existing = JSON.parse(existingRaw) as StorageWrapper<T>;
existing.values[value.id] = value
sharedFunctions.save(path, JSON.stringify(existing));
}
export function localRESTGet<T>(path: string, index?: number): WithId<T>[] {
const storage = JSON.parse(sharedFunctions.load(path) || "[]") as StorageWrapper<T>;
if (index) {
return [storage.values[index]]
}
return Object.values(storage.values)
}
export function localRESTDelete<T>(path: string, id: number) {
const existingRaw = sharedFunctions.load(path) || `{"values":{}, "currentIndex": 0}`;
const existing = JSON.parse(existingRaw) as StorageWrapper<T>;
delete existing.values[id]
sharedFunctions.save(path, JSON.stringify(existing));
}