Skip to content

Commit

Permalink
Merge pull request #140 from GetRayo/feature/middleware
Browse files Browse the repository at this point in the history
`notFound` method to have access to `middleware.`
  • Loading branch information
aichholzer committed Nov 26, 2019
2 parents fa841f5 + 54776b7 commit 99d9cc6
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 10 deletions.
17 changes: 17 additions & 0 deletions docs/examples/middleware.js
@@ -0,0 +1,17 @@
/* eslint no-console: 0 */

const rayo = require('../../packages/rayo');
const send = require('../../packages/send');

const options = {
port: 5050,
onError: (error, req, res) => res.send({ error }, 409),
notFound: (req, res) => res.send({ error: `${req.url} not found` }, 404)
};

rayo(options)
.through(send())
.get('/', (req, res, step) => step('Thrown by the step function...'))
.start((address) => {
console.log(`Up on port ${address.port}`);
});
2 changes: 1 addition & 1 deletion packages/rayo/bridge.js
Expand Up @@ -81,7 +81,7 @@ module.exports = class Bridge {
? null
: {
params: exec(path, url),
stack: this.t.concat(this.s[verb][url[0].old])
stack: this.s[verb][url[0].old]
};
}
};
22 changes: 13 additions & 9 deletions packages/rayo/index.js
Expand Up @@ -57,19 +57,23 @@ class Rayo extends Bridge {

dispatch(req, res) {
const parsedUrl = parseurl(req);
const route = this.fetch(req.method, parsedUrl.pathname);
if (!route) {
return this.notFound
? this.notFound(req, res)
: end(req, res, 404, `${req.method} ${parsedUrl.pathname} is undefined.`);
}

req.ip = ip(req);
req.params = route.params;
req.pathname = parsedUrl.pathname;
req.query = parse(parsedUrl.query);

return this.step(req, res, route.stack);
let stack;
const route = this.fetch(req.method, parsedUrl.pathname);
if (!route) {
stack = [
this.notFound ||
(() => end(req, res, 404, `${req.method} ${parsedUrl.pathname} is undefined.`))
];
} else {
req.params = route.params;
({ stack } = route);
}

return this.step(req, res, this.t.concat(stack));
}

step(req, res, stack, error = null, statusCode = 400) {
Expand Down

0 comments on commit 99d9cc6

Please sign in to comment.