Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions packages/event-handler/src/rest/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,9 +172,22 @@ export const composeMiddleware = (middleware: Middleware[]): Middleware => {
}

const middlewareFn = middleware[i];
const middlewareResult = await middlewareFn(params, reqCtx, () =>
dispatch(i + 1)
);
let nextPromise: Promise<void> | null = null;
let nextAwaited = false;
const nextFn = async () => {
nextPromise = dispatch(i + 1);
const result = await nextPromise;
nextAwaited = true;
return result;
};

const middlewareResult = await middlewareFn(params, reqCtx, nextFn);

if (nextPromise && !nextAwaited && i < middleware.length - 1) {
throw new Error(
'Middleware called next() without awaiting. This may lead to unexpected behavior.'
);
}

if (middlewareResult !== undefined) {
result = middlewareResult;
Expand Down
26 changes: 26 additions & 0 deletions packages/event-handler/tests/unit/rest/Router/middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,32 @@ describe('Class: Router - Middleware', () => {
expect(body.message).toContain('next() called multiple times');
});

it('should throw error if middleware does not await next()', async () => {
// Prepare
vi.stubEnv('POWERTOOLS_DEV', 'true');
const app = new Router();

app.use(async (_params, _reqCtx, next) => {
await next();
});

app.use(async (_params, _reqCtx, next) => {
next();
});

// Act
const result = await app.resolve(
createTestEvent('/test', 'OPTIONS'),
context
);

// Assess
const body = JSON.parse(result.body);
expect(body.message).toEqual(
'Middleware called next() without awaiting. This may lead to unexpected behavior.'
);
});

it('handles errors thrown in middleware before next()', async () => {
// Prepare
const app = new Router();
Expand Down