-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
117 lines (106 loc) · 2.44 KB
/
index.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
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import express from 'express';
import { nanoid } from 'nanoid';
const app = express();
const PORT = 3000;
const asyncWrapper = (fn) => async (req, res, next) => {
try {
return await fn(req, res);
} catch (error) {
next(error);
}
};
const memo = {};
app.use(express.json());
app.get(
'/',
asyncWrapper(async (_, res) => await res.send(JSON.stringify({ memo })))
);
app.get(
'/api/:resource',
asyncWrapper(async (req, res) => {
const {
params: { resource },
} = req;
if (!memo[resource]) {
return res.sendStatus(404);
}
return res.send(JSON.stringify(memo[resource]));
})
);
app.get(
'/api/:resource/:_id',
asyncWrapper(async (req, res) => {
const {
params: { resource, _id },
} = req;
if (!memo[resource]) {
return res.sendStatus(404);
}
const itemIndex = memo[resource].findIndex(
({ _id: itemId }) => itemId === _id
);
if (itemIndex === -1) {
return res.sendStatus(404);
}
return res.send(JSON.stringify(memo[resource][itemIndex]));
})
);
app.post(
'/api/:resource',
asyncWrapper(async (req, res) => {
const {
params: { resource },
body = {},
} = req;
const item = { ...body, _id: nanoid() };
if (memo[resource]) {
return res.send(JSON.stringify(memo[resource].push(item)));
}
memo[resource] = [item];
return res.status(200).send('1');
})
);
app.put(
'/api/:resource/:_id',
asyncWrapper(async (req, res) => {
const {
params: { resource, _id },
body = {},
} = req;
if (!memo[resource]) {
return res.sendStatus(400);
}
const itemIndex = memo[resource].findIndex(
({ _id: itemId }) => itemId === _id
);
if (itemIndex === -1) {
return res.sendStatus(404);
}
memo[resource][itemIndex] = {
...memo[resource][itemIndex],
...body,
_id,
};
return res.sendStatus(200);
})
);
app.delete(
'/api/:resource/:_id',
asyncWrapper(async (req, res) => {
const {
params: { resource, _id },
} = req;
if (!memo[resource]) {
return res.sendStatus(400);
}
const itemIndex = memo[resource].findIndex(
({ _id: itemId }) => itemId === _id
);
if (itemIndex === -1) {
return res.sendStatus(404);
}
memo[resource] = memo[resource].filter(({ _id: itemId }) => itemId === _id);
return res.sendStatus(200);
})
);
app.listen(PORT, () => console.log(`listening on port ${PORT}`));