Skip to content

Bug: Response does not get mutated when Middleware returns early #4772

@sdangol

Description

@sdangol

Expected Behavior

The Response in reqCtx.res should also get mutated when a middleware returns early when there are multiple middlewares. The middleware that would do the post processing should be able to access the response returned by the earlier middleware

Current Behavior

The Response in reqCtx.res doesn't get mutated and the post processing middleware can't access the response

Code snippet

This test fails currently as the response is not being mutated

it('allows post processing middleware to access the response returned early by a pre processing middleware', async () => {
  // Prepare
  const app = new Router();
  let message = "";
  app.get('/test', [
    async ({ reqCtx, next }) => {
      await next();
      const clonedRes = reqCtx.res.clone();
      message = (await clonedRes.json()).message;
    },
    () => {
      return Promise.resolve({ message: 'Middleware applied' })
    }
  ], () => {
    return { message: 'Handler applied' }
  });

  // Act
  await app.resolve(
    createTestEvent('/test', 'GET'),
    context
  );

  // Assess
  expect(message).toEqual('Middleware applied');
})

Steps to Reproduce

  1. Run the above unit test in the project
  2. The message is empty and hasn't been mutated

Possible Solution

Move the Response mutation logic in Router.ts to the composeMiddleware helper function

Powertools for AWS Lambda (TypeScript) version

latest

AWS Lambda function runtime

22.x

Packaging format used

npm

Execution logs

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingcompletedThis item is complete and has been merged/shippedevent-handlerThis item relates to the Event Handler Utility

Type

No type

Projects

Status

Shipped

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions