-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjson.js
69 lines (59 loc) · 1.86 KB
/
json.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
"use strict";
const express = require('express');
const serverless = require("serverless-http");
const jsonServer = require("json-server");
const request = require("request");
const middlewares = jsonServer.defaults();
const app = jsonServer.create();
app.use(middlewares);
// Route to be hit by default
app.use("/api/:fileName/:splat?", (req, res, next) => {
const { fileName, splat } = req.params;
let redirectRoute, url;
// Checking if splat exists and if yes, adding it to the end of the url
if (splat) {
url = `/${splat}${req.url}`;
} else {
url = `${req.url}`;
}
// Checking if splat is equal to filename and if not adding filename twice to the route with url
if (fileName === splat) {
redirectRoute = `/json/${fileName}${url}`;
} else {
redirectRoute = `/json/${fileName}/${fileName}${url}`;
}
// Redirecting to the json route to fetch the data.
res.redirect(307,redirectRoute);
});
// Code to return data from jsonServer
app.use("/json/:fileName/", (req, res, next) => {
const { fileName } = req.params;
const opts = {
url: `https://raw.githubusercontent.com/doselect/jsonserver/master/data/${fileName}.json`,
json: true,
};
request(opts, function (error, response, body) {
if (error) {
return res.status(400).send({ error });
}
const jsonrouter = jsonServer.router(body);
jsonrouter(req, res, next);
});
});
// Health Check
app.use("/health", (req, res, next) => {
const opts = {
url: `https://raw.githubusercontent.com/doselect/jsonserver/master/data/health_check.txt`,
json: true,
};
request(opts, function (error, response, body) {
if (error) {
return res.status(503).send({ error });
}
return res.status(200).send({ status: "Ok" });
});
});
// App to run as node server
module.exports = app;
// Handler to run as serverless
module.exports.handler = serverless(app);