File tree Expand file tree Collapse file tree 2 files changed +42
-3
lines changed Expand file tree Collapse file tree 2 files changed +42
-3
lines changed Original file line number Diff line number Diff 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 ;
Original file line number Diff line number Diff 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 ( ) ;
You can’t perform that action at this time.
0 commit comments