generated from remotelock/hiring-frontend-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_server.js
42 lines (38 loc) · 1.02 KB
/
api_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
const http = require("http");
const url = require("url");
const users = require("./api/users");
const devices = require("./api/devices");
function filterBy(collection, attr, value) {
if (!value) return collection;
const ret = {};
ret["data"] = collection["data"].filter((item) =>
new RegExp(value, "i").test(item.attributes[attr])
);
return ret;
}
const endpoints = {
"/api/users": { data: users, filter: "status" },
"/api/devices": { data: devices, filter: "name" },
};
http
.createServer(function (req, res) {
res.setHeader("Access-Control-Allow-Origin", "*");
const reqURL = url.parse(req.url, true);
const endpoint = endpoints[reqURL.pathname];
if (endpoint) {
res.writeHead(200, { "Content-Type": "applicaton/json" });
res.end(
JSON.stringify(
filterBy(
endpoint.data,
endpoint.filter,
reqURL.query[endpoint.filter]
)
)
);
} else {
res.writeHead(404);
res.end();
}
})
.listen(4000);