Middleware Logic Implementation #483
vimalmistry
started this conversation in
Ideas
Replies: 2 comments 3 replies
-
@vimalmistry FYI Promise.all() runs all the promises at the same time, so your code is running all your middleware for the route at same time, probably not what you want |
Beta Was this translation helpful? Give feedback.
1 reply
-
U can setup base middleware system smth like this: const middlewares = [
(res, req, next) => { ... },
(res, req, next) => { ... }
];
const runMiddlewares = (res, req) => {
let index = 0;
const next = async () => {
const nextMiddleware = middlewares[index++];
const hasRespondEnded = res.finished; // this is CUSTOM property, see my comment below
const shouldRunNextMiddleware = !hasRespondEnded && nextMiddleware;
if (shouldRunNextMiddleware) {
nextMiddleware(res, req, next);
}
};
next();
};
App = new App().any('/*', runMiddlewares) Unfortunately, today's HttpResponse API doesnt provide easy way to check if response has finished. const enhanceRes = (res) => {
const originalEnd = res.end.bind(res);
const originalTryEnd = res.tryEnd.bind(res);
res.finished = false;
res.end = (...args) => {
originalEnd(...args);
res.finished = true;
return res;
}
res.tryEnd = (...args) => {
const [ok, done] = originalTryEnd(...args);
res.finished = done;
return [ok, done]
}
} |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I am trying to implement middleware pipeline feature for my project.
previously I tried something ..
But I want some clean code and managing those function which returns handle functions are messy for me :(
I am trying to do something like this
Here is my handle function. Which kinda works. but If I bombard request with benchmark tool or keep refreshing tab on browser. I am getting following error. That's why I used try catch on my all code 😃
I notice that Its occurs when I
res.end
in some off middleware. I am pretty new in node js. Just working in my spare time. I am posting here so you guys can guide me or give me valuable suggestions. Thanks.Error is
Here is Example Controller and Middleware
Beta Was this translation helpful? Give feedback.
All reactions