-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
db.ts
101 lines (92 loc) · 2.42 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
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
99
100
101
import { factory, primaryKey } from '@mswjs/data';
import { nanoid } from 'nanoid';
const models = {
user: {
id: primaryKey(nanoid),
firstName: String,
lastName: String,
email: String,
password: String,
teamId: String,
role: String,
bio: String,
createdAt: Date.now,
},
team: {
id: primaryKey(nanoid),
name: String,
description: String,
createdAt: Date.now,
},
discussion: {
id: primaryKey(nanoid),
title: String,
body: String,
authorId: String,
teamId: String,
createdAt: Date.now,
},
comment: {
id: primaryKey(nanoid),
body: String,
authorId: String,
discussionId: String,
createdAt: Date.now,
},
};
export const db = factory(models);
export type Model = keyof typeof models;
const dbFilePath = 'mocked-db.json';
export const loadDb = async () => {
// If we are running in a Node.js environment
if (typeof window === 'undefined') {
const { readFile, writeFile } = await import('fs/promises');
try {
const data = await readFile(dbFilePath, 'utf8');
return JSON.parse(data);
} catch (error: any) {
if (error?.code === 'ENOENT') {
const emptyDB = {};
await writeFile(dbFilePath, JSON.stringify(emptyDB, null, 2));
return emptyDB;
} else {
console.error('Error loading mocked DB:', error);
return null;
}
}
}
// If we are running in a browser environment
return Object.assign(
JSON.parse(window.localStorage.getItem('msw-db') || '{}'),
);
};
export const storeDb = async (data: string) => {
// If we are running in a Node.js environment
if (typeof window === 'undefined') {
const { writeFile } = await import('fs/promises');
await writeFile(dbFilePath, data);
} else {
// If we are running in a browser environment
window.localStorage.setItem('msw-db', data);
}
};
export const persistDb = async (model: Model) => {
if (process.env.NODE_ENV === 'test') return;
const data = await loadDb();
data[model] = db[model].getAll();
await storeDb(JSON.stringify(data));
};
export const initializeDb = async () => {
const database = await 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();
};