Performance: Middleware patterns
Middleware patterns affect request processing speed and server response time by adding layers of code that run before the final handler.
app.use(async (ctx, next) => { await Promise.all([someHeavyTask(), anotherHeavyTask()]); await next(); }); app.use(async (ctx) => { ctx.response.body = 'Done'; });
app.use(async (ctx, next) => { await someHeavyTask(); await next(); }); app.use(async (ctx, next) => { await anotherHeavyTask(); await next(); }); app.use(async (ctx) => { ctx.response.body = 'Done'; });
| Pattern | Middleware Count | Sequential Tasks | Parallel Tasks | Verdict |
|---|---|---|---|---|
| Sequential heavy middleware | 3 | 3 | 0 | [X] Bad |
| Parallelized middleware tasks | 2 | 2 | 2 | [OK] Good |
async function logger(ctx, next) {
console.log('Before');
await next();
console.log('After');
}
async function handler(ctx) {
ctx.response.body = 'Hello';
}
// Middleware chain: logger -> handler
What will be printed to the console when a request is handled?async function auth(ctx, next) {
if (!ctx.request.headers.get('Authorization')) {
ctx.response.status = 401;
ctx.response.body = 'Unauthorized';
}
await next();
}X-Response-Time with the duration in milliseconds. Which of the following middleware implementations correctly achieves this?Pass the test and this pattern moves unknown