forked from jerrynavi/express-oas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.js
65 lines (56 loc) · 1.42 KB
/
database.js
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
function mockDatabase() {
const dataStore = [];
function userExists(id) {
return dataStore.findIndex((value) => value.id === id) !== -1;
}
function addUser(data) {
if (userExists(data.id)) {
// user already exists, let's throw an error
throw new Error("User already exists.");
}
dataStore.push(data);
}
function updateUser(id, data) {
if (!userExists(id)) {
// user does not exist, let's throw an error
throw new Error(`No user with ID ${id} was found`);
}
const index = dataStore.findIndex((value) => value.id === id);
const updatedUser = {
...dataStore[index],
...data,
id,
};
dataStore.splice(index, 1, updatedUser);
return updatedUser;
}
function deleteUser(id) {
if (!userExists(id)) {
// user does not exist, let's throw an error
throw new Error(`No user with ID ${id} was found`);
}
dataStore.splice(
dataStore.findIndex((value) => value.id === id),
1
);
}
function getAll() {
return dataStore;
}
function getOne(id) {
if (!userExists(id)) {
// user does not exist, let's throw an error
throw new Error(`No user with ID ${id} was found`);
}
return dataStore.find((value) => value.id === id);
}
return {
addUser,
updateUser,
deleteUser,
getAll,
getOne,
};
}
const mockDatabaseInstance = mockDatabase();
export default mockDatabaseInstance;