This repository has been archived by the owner on Dec 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
health-codefather-api.js
101 lines (87 loc) · 2.55 KB
/
health-codefather-api.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
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const fs = require('fs');
const mockApiUtils = require('./mock-api-utils');
const app = express();
// parse application/json
app.use(bodyParser.json());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
// set the port of our application
// process.env.PORT lets the port be set by Heroku
const port = process.env.PORT || 3030;
const dataDir = __dirname + '/data';
app.get('/lgaBounds', (req, res) => {
res.send(fs.readFileSync('./data/simpleLgaRegions.json'))
});
app.all('/*', (req, res) => {
switch (req.method) {
case 'GET':
console.log('✅ [GET]', req.url);
handleGeneric(req, res);
break;
case 'POST':
console.log('✅ [POST]', req.url, req.body);
handlePOST(req, res);
break;
case 'PUT':
console.log('✅ [PUT]', req.url, req.body);
handleGeneric(req, res);
break;
case 'DELETE':
console.log('✅ [DELETE]', req.url, req.body);
handleGeneric(req, res);
break;
default:
res.status(500).send(`Unrecognized method ${req.method}`);
}
});
const errorResponse = res => {
res
.status(500)
.send("Couldn't satisfy your request, please see server logs.");
};
const handleGET = async (req, res, fallback = errorResponse) => {
let response;
if (req.url.includes('contactDetails') || req.url.includes('simpleLgaRegions')) {
response = mockApiUtils.loadResponseData(dataDir, req.url, req.query);
} else {
response = await mockApiUtils.loadResponseDataAsJSON(dataDir, req.url, req.query);
}
if (response) {
console.log('✅ [GET]', req.url);
res.setHeader('Content-Type', 'application/json');
res.send(response);
} else {
fallback(req, res);
}
};
const handleGeneric = handleGET;
const handlePOST = (req, res, fallback = errorResponse) => {
const response = mockApiUtils.loadResponseData(dataDir, req.url, req.query);
if (response) {
console.log('✅ [POST]', req.url);
res.status(200).send(response);
} else {
fallback(req, res);
}
};
const sendErrorResponse = res => {
setTimeout(function() {
res.status(500).send(() => {});
});
return;
};
const handlePUT = (req, res) => {
console.log('✅ [PUT]', req.url, req.body);
res.sendStatus(200);
};
const handleDELETE = (req, res) => {
console.log('✅ [DELETE]', req.url, req.body);
res.sendStatus(200);
};
app.listen(port, function() {
console.log(`listening on ${port} 🛰`);
});