-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
199 lines (160 loc) · 5.03 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
'use strict';
const topLogPrefix = 'larvitrouter: index.js: ';
const { Log } = require('larvitutils');
const LRU = require('lru-cache');
const path = require('path');
const fs = require('fs');
class Router {
/**
* Module main constructor
*
* @param {obj} options - {
* basePath: process.cwd(),
* cacheMax: 1000,
* paths: {
* controller: {
* path': 'controllers',
* exts: 'js'
* },
* static: {
* path: 'public',
* exts: false
* },
* template: {
* path: 'public/templates',
* exts: ['tmpl', 'tmp', 'ejs', 'pug']
* }
* },
* routes: [],
* log: log object,
* }
*/
constructor(options) {
const logPrefix = topLogPrefix + 'Router() - ';
let defaultRouteFound = false;
if (!options) options = {};
this.options = options;
if (!options.paths) {
options.paths = {
controller: {
path: 'controllers',
exts: 'js'
},
static: {
path: 'public',
exts: false
},
template: {
path: 'public/templates',
exts: ['tmpl', 'tmp', 'ejs', 'pug']
}
};
}
if (!options.basePath) options.basePath = process.cwd();
if (!options.routes) options.routes = [];
if (!options.log) {
options.log = new Log();
}
const log = options.log;
for (const key of Object.keys(options.paths)) {
if (!Array.isArray(options.paths[key].exts) && options.paths[key].exts !== false) {
options.paths[key].exts = [options.paths[key].exts];
}
}
for (let i = 0; options.routes[i] !== undefined; i++) {
if (options.routes[i].regex === '^/$') {
defaultRouteFound = true;
break;
}
}
// We should always have a default route, so if none exists, create one
if (defaultRouteFound === false) {
options.routes.push({
regex: '^/$',
controllerPath: 'default.js',
templatePath: 'default.tmpl'
});
}
for (const key of Object.keys(options)) {
this[key] = options[key];
}
this.cache = new LRU({ max: options.cacheMax || 5000 });
// eslint-disable-next-line no-unused-vars
const {log: unused, ...optionsWithoutLog} = options;
log.debug(logPrefix + 'Instantiated with options: ' + JSON.stringify(optionsWithoutLog));
}
getFullPath(relPath) {
const fullPath = path.join(this.basePath, relPath);
const result = fs.existsSync(fullPath) ? fullPath : false;
return result;
}
resolve(urlStr, cb) {
const logPrefix = topLogPrefix + 'Router.prototype.resolve() - ';
const result = {};
const { log, routes } = this.options;
if (typeof cb !== 'function') {
cb = () => {};
}
if (typeof urlStr !== 'string') {
const err = new Error('First parameter must be a string');
log.warn(logPrefix + err.message);
log.verbose(logPrefix + 'err.stack:\n' + err.stack);
return cb(err);
}
log.debug(logPrefix + 'parsing URL ' + urlStr);
const relUrlStr = path.normalize(urlStr[0] === '/' ? urlStr.substring(1) : urlStr);
// SECURITY! Someone is trying to find paths above the given route root
if (relUrlStr.startsWith('..')) {
log.info(logPrefix + 'Security! Stopped try to route a route above the route root: "' + relUrlStr);
return cb(null, result);
}
// Check cache and return if found
const cachedResult = this.cache.get(relUrlStr);
if (cachedResult !== undefined) {
log.debug(logPrefix + 'Found router entry in cache, urlStr: ' + urlStr);
return cb(null, cachedResult);
}
// Go through all custom routes to see if we have a match
for (let i = 0; this.routes[i] !== undefined; i++) {
log.silly(logPrefix + 'Trying to match custom route "' + routes[i].regex + '" with urlStr "' + urlStr + '"');
if (RegExp(routes[i].regex).test(urlStr)) {
log.debug(logPrefix + 'Matched custom route "' + routes[i].regex + '" to route: ' + JSON.stringify(routes[i]));
for (const key of Object.keys(routes[i])) {
if (key !== 'regex') {
result[key] = routes[i][key];
}
}
break; // Break execution, no need to go through the rest
}
}
// If no route is matched, try to autoresolve stuff
if (Object.keys(result).length === 0) {
for (const type of Object.keys(this.paths)) {
const routeOpts = this.paths[type];
if (!Array.isArray(routeOpts.exts) && this.getFullPath(routeOpts.path + '/' + relUrlStr)) {
result[type + 'Path'] = relUrlStr;
} else {
for (let i = 0; routeOpts.exts[i] !== undefined; i++) {
const ext = routeOpts.exts[i];
if (this.getFullPath(routeOpts.path + '/' + relUrlStr + '.' + ext)) {
result[type + 'Path'] = relUrlStr + '.' + ext;
}
}
}
}
}
// Set full paths where missing
for (const type of Object.keys(this.paths)) {
const routeOpts = this.paths[type];
if (result[type + 'Path'] && !result[type + 'FullPath']) {
result[type + 'FullPath'] = this.getFullPath(routeOpts.path + '/' + result[type + 'Path']);
if (!result[type + 'FullPath']) {
log.warn(logPrefix + 'Could not find full path for ' + type + 'Path: ' + result[type + 'Path']);
}
}
}
this.cache.set(relUrlStr, result);
cb(null, result);
}
}
exports = module.exports = Router;