Skip to content

Commit

Permalink
feat(router): parsing routes and validating verbs
Browse files Browse the repository at this point in the history
  • Loading branch information
reel committed Nov 23, 2017
1 parent ca868b6 commit bc4fe93
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 13 deletions.
59 changes: 46 additions & 13 deletions packages/router/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,8 @@ async function init(reload = false) {
}

for (const key in routes) {
let controller = routes[key];
const routeKey = key.split(' ');
let verb = routeKey.length > 1 ? routeKey[0].toLowerCase() : 'get';
let route =
routeKey.length > 1 ? routeKey[1].replace('/', '') : key.replace('/', '');
if (typeof controller === 'string') {
controller = { controller: controller };
}
const [verb, route, controller] = parseRoute(key, routes[key]);

if (verb === 'resources') {
const scope = controller.scope ? `/${controller.scope}/` : '/';
controller.resources = route;
Expand Down Expand Up @@ -67,11 +61,8 @@ async function init(reload = false) {
}

for (const key in routes) {
const controller = routes[key].controller;
const roles = routes[key].roles || null;
const routeKey = key.split(' ');
let verb = routeKey.length > 1 ? routeKey[0].toLowerCase() : 'get';
let route = routeKey.length > 1 ? routeKey[1] : key;
const [verb, route, opts] = parseRoute(key, routes[key]);
const { roles, controller } = opts;

if (controllers.hasOwnProperty(controller)) {
register(verb, route, routes[key], controllers[controller], roles);
Expand Down Expand Up @@ -168,6 +159,48 @@ function middlewares(router) {
});
}

const parseRoute = (key, args) => {
let controller = args;
const routeKey = key.split(' ');
let verb = routeKey.length > 1 ? routeKey[0].toLowerCase() : 'get';
let route = routeKey.length > 1 ? routeKey[1] : key;
if (typeof controller === 'string') {
controller = { controller: controller };
}
if (!verbs.includes(verb)) {
verb = 'get';
log.warn(`the verb used in ${key} is unknown. using GET instead.`);
}
return [verb, route, controller];
};

const verbs = [
'checkout',
'copy',
'delete',
'get',
'head',
'lock',
'merge',
'mkactivity',
'mkcol',
'move',
'm-search',
'notify',
'options',
'patch',
'post',
'purge',
'put',
'report',
'search',
'subscribe',
'trace',
'unlock',
'unsubscribe',
'resources',
];

async function reload() {
await init(true);
log.warn('routes reloaded');
Expand Down
1 change: 1 addition & 0 deletions packages/router/tests/main.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ describe('router', () => {
});
test('fs routes', () => {
const routes = henri._routes;
console.dir(henri);
expect(routes['get /fs'].active).toBeFalsy();
expect(routes['get /unfs'].active).toBeFalsy();
});
Expand Down

0 comments on commit bc4fe93

Please sign in to comment.