forked from LearnToCodeGrandRapids/node-rest-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.js
More file actions
52 lines (38 loc) · 1.16 KB
/
database.js
File metadata and controls
52 lines (38 loc) · 1.16 KB
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
const doggos = require("./doggos.json");
const state = {
primaryKey: 1,
database: []
};
const database = {
initialize: items =>
(state.database = items.map(item => ({
id: state.primaryKey++,
...item
}))),
getAll: () => state.database,
getById: id => state.database.find(item => item.id === id),
getByAttribute: (attribute, value) =>
state.database.filter(
item => item[attribute].toLowerCase() === value.toLowerCase()
),
create: item => {
const newItem = { id: state.primaryKey++, ...item };
state.database.push(newItem);
return newItem;
},
update: (id, item) => {
const index = state.database.findIndex(item => item.id === id);
const updatedItem = { ...state.database[index], id, ...item };
state.database[index] = updatedItem;
return updatedItem;
},
put: (id, item) => {
const index = state.database.findIndex(item => item.id === id);
const updatedItem = { id, ...item };
state.database[index] = updatedItem;
return updatedItem;
},
delete: id => (state.database = state.database.filter(item => item.id !== id))
};
database.initialize(doggos);
module.exports = database;