-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
43 lines (38 loc) · 1.14 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
var path = require('path');
var ls = require('ls-sync');
var route = require('koa-route');
var rewrite = require('koa-rewrite');
module.exports = function (app, options) {
if (typeof options === 'string') {
options = {root: options};
} else if (!options || !options.root) {
throw new Error('`root` config required.');
}
var wildcard = options.wildcard || '*';
var root = options.root;
//rewrite / to /index
app.use(rewrite('/', '/index'));
ls(root).forEach(function (filePath) {
if (path.extname(filePath) !== '.js') {
return;
}
var exportFuncs = require(filePath);
var pathRegexp = formatPath(filePath, root, wildcard);
for (var method in exportFuncs) {
try {
exportFuncs[method].pathRegexp = pathRegexp;
app.use(route[method.toLowerCase()](pathRegexp, exportFuncs[method]));
} catch (e) {}
};
});
return function* frouter(next) {
yield* next;
};
};
function formatPath(filePath, root, wildcard) {
return filePath
.replace(path.resolve(process.cwd(), root), '')
.replace(/\\/g, '/')
.replace(new RegExp('/\\' + wildcard, 'g'), '/:')
.split('.')[0];
}