forked from jung-han/test-hang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
76 lines (60 loc) · 1.81 KB
/
Copy pathserver.js
File metadata and controls
76 lines (60 loc) · 1.81 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { randomUUID } from 'crypto';
import fs from 'fs';
import { readFile } from 'fs/promises';
import path from 'path';
import express from 'express';
const app = express();
const port = 3000;
const __dirname = path.resolve();
app.use(express.json());
const getEvents = async () => {
const data = await readFile(`${__dirname}/src/__mocks__/response/realEvents.json`, 'utf8');
return JSON.parse(data);
};
app.get('/api/events', async (_, res) => {
const events = await getEvents();
res.json(events);
});
app.post('/api/events', async (req, res) => {
const events = await getEvents();
const newEvent = { id: randomUUID(), ...req.body };
fs.writeFileSync(
`${__dirname}/src/__mocks__/response/realEvents.json`,
JSON.stringify({
events: [...events.events, newEvent],
})
);
res.status(201).json(newEvent);
});
app.put('/api/events/:id', async (req, res) => {
const events = await getEvents();
const { id } = req.params;
const eventIndex = events.events.findIndex((event) => event.id === id);
if (eventIndex > -1) {
const newEvents = [...events.events];
newEvents[eventIndex] = { ...events.events[eventIndex], ...req.body };
fs.writeFileSync(
`${__dirname}/src/__mocks__/response/realEvents.json`,
JSON.stringify({
events: newEvents,
})
);
res.json(events.events[eventIndex]);
} else {
res.status(404).send('Event not found');
}
});
app.delete('/api/events/:id', async (req, res) => {
const events = await getEvents();
const { id } = req.params;
fs.writeFileSync(
`${__dirname}/src/__mocks__/response/realEvents.json`,
JSON.stringify({
events: events.events.filter((event) => event.id !== id),
})
);
res.status(204).send();
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});