-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
109 lines (95 loc) · 3.17 KB
/
index.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
102
103
104
105
106
107
108
109
let restify = require("restify");
const corsMiddleware = require("restify-cors-middleware");
const config = require("./gravity.config");
const Plasma = require("plasma");
const GravityException = require("./GravityException");
let server = null;
module.exports.start = function(callback){
if(server === null){
initializeDB();
initializeServer(callback);
}else{
throw new Error("Server already initialized");
}
};
module.exports.stop = function(callback){
if(server !== null){
server.close(() => {
server = null;
if(callback !== undefined) {
callback();
}
});
}else{
throw new Error("Server not initialized");
}
};
function initializeDB(){
let database = new Plasma();
database.connect(config.db);
}
function initializeServer(callback){
server = restify.createServer({
name: 'Gravity Server',
version: process.env.npm_package_version
});
const cors = corsMiddleware({
origins: ['*']
});
server.pre(cors.preflight);
server.use(cors.actual);
server.use(restify.plugins.acceptParser(server.acceptable));
server.use(restify.plugins.queryParser());
server.use(restify.plugins.bodyParser());
server.listen(config.port, () => {
if(callback !== undefined){
callback(server.name, server.url);
}
});
loadEndpoint(config.endpoints);
}
function loadEndpoint(endpoints, parentPath = []){
for(let path in endpoints){
if(endpoints.hasOwnProperty(path)){
let endpoint = endpoints[path];
let fullPath = "";
for(let i = 0; i < parentPath.length; i++){
fullPath += "/" + parentPath[i];
}
fullPath += "/" + path;
if(endpoint.handler !== undefined && typeof endpoint.handler !== typeof Function){
throw new Error("Endpoint configuration '" + fullPath + "' has invalid handler type");
}
if(typeof endpoint.method === typeof '' && endpoint.handler !== undefined){
server[endpoint.method](fullPath, handlerErrorWrapper(endpoint.handler));
}
if(endpoint.children !== undefined){
let childPaths = [].concat(parentPath);
childPaths.push(path);
loadEndpoint(endpoint.children, childPaths);
}
}else{
throw new Error("Endpoints configuration object somehow missing key '" + path.toString() + "' when its known to be in itself");
}
}
}
function handlerErrorWrapper(handler){
return function(req, res, next){
let wrapped_next = function(e){
if(e !== undefined){
if(!(e instanceof GravityException)){
e = new GravityException(e);
}
if(e instanceof GravityException){
res.status(e.status);
res.send({
error: e.code,
error_description: e.description
});
}
}
next();
};
handler(req, res, wrapped_next);
};
}