U can setup base middleware system smth like this:
haoynmail opened this issue · 1 comments
haoynmail commented
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.
For now you propably might want to override the res.end and res.tryEnd methods:
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]
}
}
Originally posted by @kolodziejczak-sz in #483 (comment)
haoynmail commented
hello @kolodziejczak-sz
Please advise on the use about const enhanceRes=(res)=>{...}.
For example, I have a middleware array:
const middleware=[
(res, req, next)=>{...},
(res, req, next)=>{...}, (this position res.end (...), not executed later)
(res, req, next)=>{...},
];
I want the second middleware to send messages to the browser, while the third middleware does not execute. How to use enhancRes (res)