forked from lsongdev/koa-routeify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.js
44 lines (40 loc) · 1.19 KB
/
parser.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
var fs = require('fs');
var pathToRegexp = require('path-to-regexp');
const TAG = {
TO : '=>',
EOL : '\n',
SPACE : /\s+/,
SHARP : '#',
};
function removeQuotes(input){
return input.map(function(item){
return item.trim().replace(/"|'/ig, '')
});
};
exports.removeQuotes = removeQuotes;
module.exports = function parseRoute(filename){
var content = fs.readFileSync(filename);
var routes = content.toString().split(TAG.EOL).map(function(line){
return line.trim();
}).filter(function(line){
return line !== '' && (!(/^\/\//).test(line));
}).map(function(line){
return line.split(TAG.TO).map(function(str){
return str.trim();
});
}).map(function(item){
if(item.length < 2){
throw new Error('invalidate route define', item);
}
var method_and_route = removeQuotes(item[0].split(TAG.SPACE));
var controller_and_action = removeQuotes(item[1].split(TAG.SHARP));
return {
route : method_and_route[1],
method : method_and_route[0].toUpperCase(),
regexp : pathToRegexp(method_and_route[1]),
controller : controller_and_action[0],
action : controller_and_action[1]
}
});
return routes;
};