-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
75 lines (62 loc) · 2.06 KB
/
server.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
const jsonServer = require('json-server');
const clone = require('clone');
const data = require('./db.json');
const cors = require('cors');
const isProductionEnv = process.env.NODE_ENV === 'production';
const server = jsonServer.create();
server.use(cors({
origin: '*',
}));
server.use((req, res, next) => {
res.set("Cross-Origin-Resource-Policy", "cross-origin");
next();
});
const customHeadersMiddleware = (req, res, next) => {
// Set custom headers
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Cross-Origin-Resource-Policy', '*');
// Continue with the next middleware or route handler
next();
};
// For mocking the POST request, POST request won't make any changes to the DB in production environment
const router = jsonServer.router(isProductionEnv ? clone(data) : 'db.json', {
_isFake: isProductionEnv
});
const middlewares = jsonServer.defaults();
server.use(middlewares);
server.use(customHeadersMiddleware);
// Custom route to update a template
server.put('/templates/:purpose/:id', (req, res) => {
const id = req.params.id;
const purpose = req.params.purpose;
const updatedTemplate = req.body;
const db = router.db; // Get the lowdb instance
// Find the template by id and update it
let template = db.get(purpose)
.find({ id: id })
.assign(updatedTemplate)
.write();
res.json(template);
});
// Custom route to add a new template
server.post('/templates/:purpose', (req, res) => {
const purpose = req.params.purpose;
const newTemplate = req.body;
const db = router.db; // Get the lowdb instance
// Add the new template to the database
let template = db.get(purpose)
.push(newTemplate)
.write();
res.status(201).json(template);
});
server.use((req, res, next) => {
if (req.path !== '/')
router.db.setState(clone(data));
next();
});
server.use(router);
server.listen(process.env.PORT || 8000, () => {
console.log('JSON Server is running at : http://localhost:8000');
});
// Export the Server API
module.exports = server;