Skip to content

Commit

Permalink
Use expressjs Layer matching
Browse files Browse the repository at this point in the history
  • Loading branch information
flovilmart committed Jul 18, 2016
1 parent 50a5305 commit b78edda
Showing 1 changed file with 27 additions and 30 deletions.
57 changes: 27 additions & 30 deletions src/PromiseRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,22 @@ import {
logResponse
} from './SensitiveLogger';

const Layer = require('express/lib/router/layer');

function validateParameter(key, value) {
if (key == 'className') {
if (value.match(/_?[A-Za-z][A-Za-z_0-9]*/)) {
return value;
}
}else if (key == 'objectId') {
if (value.match(/[A-Za-z0-9]+/)) {
return value;
}
} else {
return value;
}
}

export default class PromiseRouter {
// Each entry should be an object with:
// path: the path to route, in express format
Expand Down Expand Up @@ -69,7 +85,8 @@ export default class PromiseRouter {
this.routes.push({
path: path,
method: method,
handler: handler
handler: handler,
layer: new Layer(path, null, handler)
});
};

Expand All @@ -82,36 +99,16 @@ export default class PromiseRouter {
if (route.method != method) {
continue;
}
// NOTE: we can only route the specific wildcards :className and
// :objectId, and in that order.
// This is pretty hacky but I don't want to rebuild the entire
// express route matcher. Maybe there's a way to reuse its logic.
var pattern = '^' + route.path + '$';

pattern = pattern.replace(':className',
'(_?[A-Za-z][A-Za-z_0-9]*)');
pattern = pattern.replace(':objectId',
'([A-Za-z0-9]+)');
pattern = pattern.replace(':functionName',
'([A-Za-z0-9_]+)');

var re = new RegExp(pattern);
var m = path.match(re);
if (!m) {
continue;
}
var params = {};
if (m[1]) {
params.className = m[1];
}
if (m[2]) {
params.objectId = m[2];
}
if (route.path.indexOf(':functionName') > 0) {
params.functionName = m[1];
}

return {params: params, handler: route.handler};
let layer = route.layer || new Layer(route.path, null, route.handler);
let match = layer.match(path);
if (match) {
let params = layer.params;
Object.keys(params).forEach((key) => {
params[key] = validateParameter(key, params[key]);
});
return {params: params, handler: route.handler};
}
}
};

Expand Down

0 comments on commit b78edda

Please sign in to comment.