Skip to content

Commit b0b43e8

Browse files
svozzadreamorosi
andauthored
feat(event-handler): throw error when middleware does not await next() (#4511)
Co-authored-by: Andrea Amorosi <[email protected]>
1 parent c45206b commit b0b43e8

File tree

2 files changed

+42
-3
lines changed

2 files changed

+42
-3
lines changed

packages/event-handler/src/rest/utils.ts

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -172,9 +172,22 @@ export const composeMiddleware = (middleware: Middleware[]): Middleware => {
172172
}
173173

174174
const middlewareFn = middleware[i];
175-
const middlewareResult = await middlewareFn(params, reqCtx, () =>
176-
dispatch(i + 1)
177-
);
175+
let nextPromise: Promise<void> | null = null;
176+
let nextAwaited = false;
177+
const nextFn = async () => {
178+
nextPromise = dispatch(i + 1);
179+
const result = await nextPromise;
180+
nextAwaited = true;
181+
return result;
182+
};
183+
184+
const middlewareResult = await middlewareFn(params, reqCtx, nextFn);
185+
186+
if (nextPromise && !nextAwaited && i < middleware.length - 1) {
187+
throw new Error(
188+
'Middleware called next() without awaiting. This may lead to unexpected behavior.'
189+
);
190+
}
178191

179192
if (middlewareResult !== undefined) {
180193
result = middlewareResult;

packages/event-handler/tests/unit/rest/Router/middleware.test.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,32 @@ describe('Class: Router - Middleware', () => {
180180
expect(body.message).toContain('next() called multiple times');
181181
});
182182

183+
it('should throw error if middleware does not await next()', async () => {
184+
// Prepare
185+
vi.stubEnv('POWERTOOLS_DEV', 'true');
186+
const app = new Router();
187+
188+
app.use(async (_params, _reqCtx, next) => {
189+
await next();
190+
});
191+
192+
app.use(async (_params, _reqCtx, next) => {
193+
next();
194+
});
195+
196+
// Act
197+
const result = await app.resolve(
198+
createTestEvent('/test', 'OPTIONS'),
199+
context
200+
);
201+
202+
// Assess
203+
const body = JSON.parse(result.body);
204+
expect(body.message).toEqual(
205+
'Middleware called next() without awaiting. This may lead to unexpected behavior.'
206+
);
207+
});
208+
183209
it('handles errors thrown in middleware before next()', async () => {
184210
// Prepare
185211
const app = new Router();

0 commit comments

Comments
 (0)