forked from alan2207/bulletproof-react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.ts
67 lines (59 loc) · 1.39 KB
/
db.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
import { factory, primaryKey } from '@mswjs/data';
const models = {
user: {
id: primaryKey(String),
firstName: String,
lastName: String,
email: String,
password: String,
teamId: String,
role: String,
bio: String,
createdAt: Number,
},
team: {
id: primaryKey(String),
name: String,
description: String,
createdAt: Number,
},
discussion: {
id: primaryKey(String),
title: String,
body: String,
teamId: String,
createdAt: Number,
},
comment: {
id: primaryKey(String),
body: String,
authorId: String,
discussionId: String,
createdAt: Number,
},
};
export const db = factory(models);
export type Model = keyof typeof db;
export const loadDb = () =>
Object.assign(JSON.parse(window.localStorage.getItem('msw-db') || '{}'));
export const persistDb = (model: Model) => {
if (process.env.NODE_ENV === 'test') return;
const data = loadDb();
data[model] = db[model].getAll();
window.localStorage.setItem('msw-db', JSON.stringify(data));
};
export const initializeDb = () => {
const database = loadDb();
Object.entries(db).forEach(([key, model]) => {
const dataEntres = database[key];
if (dataEntres) {
dataEntres?.forEach((entry: Record<string, any>) => {
model.create(entry);
});
}
});
};
export const resetDb = () => {
window.localStorage.clear();
};
initializeDb();