-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb-api.js
More file actions
60 lines (48 loc) · 1.93 KB
/
Copy pathweb-api.js
File metadata and controls
60 lines (48 loc) · 1.93 KB
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
var _ = require('lodash');
var bodyParser = require('body-parser')
module.exports.register = function(app, controllerList, prefix){
prefix = prefix || '';
app.use(bodyParser.json());
for(var i = 0; i < controllerList.length; i++){
registerController(controllerList[i]);
}
function registerController(controller){
var controllerName = functionName(controller);
if(_.endsWith(controllerName, 'Controller')){
controllerName = controllerName.substring(0, controllerName.length - 10);
}
var cont = new controller;
_.each(_.keys(cont), function(name){
var route = prefix + '/' + controllerName + '/';
if(_.startsWith(name, 'post')) {
registerRoute('post', route + name.substring(4), cont[name]);
} else if(_.startsWith(name, 'put')) {
registerRoute('put', route + name.substring(3), cont[name]);
} else if(_.startsWith(name, 'delete')) {
registerRoute('delete', route + name.substring(6), cont[name]);
} else if(_.startsWith(name, 'get')) {
registerRoute('get', route + name.substring(3), cont[name]);
}
});
}
function registerRoute(method, route, func){
console.log(route);
app[method](route, function(req, res){
func(req, res, req.query, req.body);
});
}
function functionName( func )
{
// Match:
// - ^ the beginning of the string
// - function the word 'function'
// - \s+ at least some white space
// - ([\w\$]+) capture one or more valid JavaScript identifier characters
// - \s* optionally followed by white space (in theory there won't be any here,
// so if performance is an issue this can be omitted[1]
// - \( followed by an opening brace
//
var result = /^function\s+([\w\$]+)\s*\(/.exec( func.toString() )
return result ? result[ 1 ] : '' // for an anonymous function there won't be a match
}
}