Skip to content

Commit

Permalink
Adding next attribute to req for conditional "skipping" to the en…
Browse files Browse the repository at this point in the history
…d of the middleware
  • Loading branch information
avoidwork committed Oct 24, 2019
1 parent f8b6315 commit 14cec1b
Show file tree
Hide file tree
Showing 5 changed files with 14 additions and 6 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ Sends an error response.
##### res.header (key, value)
Shorthand of `res.setHeader()`.

##### res.next (req, res, next)
First middleware of the HTTP method as a way to "skip" to the middleware which sends a response; will not work if the target middleware calls `next()`!.

##### res.json (body, [status = 200, headers])
Sends a JSON response.

Expand Down
8 changes: 6 additions & 2 deletions lib/utility.js
Original file line number Diff line number Diff line change
Expand Up @@ -166,12 +166,16 @@ function pipeable (method, arg) {
return method !== "HEAD" && arg !== null && typeof arg.on === "function";
}

function reduce (uri, map = new Map(), arg = {}) {
function reduce (uri, map = new Map(), arg = {}, first = false) {
Array.from(map.entries()).filter(i => {
i[0].lastIndex = 0;

return i[0].test(uri);
}).forEach(i => {
}).forEach((i, idx) => {
if (idx === 0 && first) {
arg.next = i[1].handlers[0];
}

arg.middleware = [...arg.middleware, ...i[1].handlers];

if (i[1].pos.length > 0 && arg.pos.length === 0) {
Expand Down
5 changes: 3 additions & 2 deletions lib/woodland.js
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,7 @@ class Woodland extends EventEmitter {
params(req, result.pos);
}

req.next = result.next;
next(req, res, e, result.middleware[Symbol.iterator]())();
} else {
last(req, res, e);
Expand All @@ -410,11 +411,11 @@ class Woodland extends EventEmitter {
if (cached !== void 0) {
result = cached;
} else {
result = {middleware: [], params: false, pos: [], visible: 0};
result = {middleware: [], params: false, pos: [], visible: 0, next: null};
reduce(uri, this.middleware.get(all), result);

if (method !== all) {
reduce(uri, this.middleware.get(method), result);
reduce(uri, this.middleware.get(method), result, true);
}

result.visible = result.middleware.filter(i => this.blacklisted.has(i) === false).length;
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "woodland",
"version": "9.0.1",
"version": "9.1.0",
"description": "Lightweight HTTP/HTTP2 router with automatic `Allow` & `CORS` headers",
"main": "index.js",
"scripts": {
Expand Down

0 comments on commit 14cec1b

Please sign in to comment.