-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
77 lines (69 loc) · 1.75 KB
/
app.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
const Koa = require('koa');
const cors = require('@koa/cors');
const Router = require('koa-router');
const chalk = require('chalk');
const app = new Koa();
const router = new Router();
let server;
let initialRoutes;
let currentRoutes;
const loadRoutes = (routes) => {
Object.keys(routes).forEach(path => {
const config = routes[path];
router[config.use.toLowerCase()](path, ctx => {
const response = config.responses.find(({ query = {} }) => {
let matches = true;
Object.keys(query).forEach(key => {
if(query[key] !== ctx.query[key]) {
matches = false;
}
});
return matches;
});
if(response) {
ctx.status = response.status;
ctx.body = response.response;
}
});
});
};
const start = (routes, port = 3001) => {
if (typeof routes !== 'object') {
console.log(chalk.red('Routes are not a valid json object - exiting.'));
return;
}
app.use(cors({ origin: "*", allowHeaders: "*" }));
initialRoutes = { ...routes };
currentRoutes = { ...routes };
loadRoutes(initialRoutes);
app.use(router.routes());
server = app.listen(port);
console.log(`server listening on port: ${port}`)
};
const stop = () => {
if (server) {
server.close();
server = undefined;
} else {
console.log(chalk.yellow('Called `stop` before server was started'));
}
};
const restore = () => {
if (typeof initialRoutes !== 'object') {
console.log(chalk.yellow('Called `restore` before server was started'));
return;
}
router.stack = [];
loadRoutes(initialRoutes);
};
const add = (routes) => {
currentRoutes = { ...currentRoutes, ...routes };
router.stack = [];
loadRoutes(currentRoutes);
};
module.exports = {
start,
stop,
restore,
add,
};