-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.ts
56 lines (52 loc) · 1.24 KB
/
database.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
// global.cache is needed because of how remix local dev works
// see https://remix.run/docs/en/v1/other-api/serve
declare module global {
let db: TodoItem[]
let idTracker: number
let hasLoaded: boolean
}
export type TodoItem = {
id: number
completed?: boolean
deleted?: boolean
description: string
}
const newId = () => {
global.idTracker = (global.idTracker ?? 0) + 1
return global.idTracker
}
export const db = {
load: () => global.db ?? [],
save: function (
items: (Omit<TodoItem, 'id'> & Partial<Pick<TodoItem, 'id'>>)[],
) {
global.db = items.map(t => ({
...t,
id: t.id ?? newId(),
}))
return global.db
},
patch: function (id: number, patch: Partial<Omit<TodoItem, 'id'>>) {
global.db = global.db.map(t =>
t.id !== id
? t
: {
...t,
...patch,
},
)
},
append: (item: Omit<TodoItem, 'id'> & Partial<Pick<TodoItem, 'id'>>) =>
db.save([...db.load(), item]),
populateSample: () => {
db.save([
{ description: 'Pet the cat' },
{ description: 'Bath the cat' },
{ description: 'Attend hospital due to cat related injuries' },
])
},
}
if (!global.hasLoaded) {
db.populateSample()
global.hasLoaded = true
}