elysiajs / elysia

Ergonomic Framework for Humans
https://elysiajs.com
MIT License
10.59k stars 226 forks source link

inconsistent map-response behavior #854

Open ap0nia opened 1 month ago

ap0nia commented 1 month ago

What version of Elysia is running?

1.1.16

What platform is your computer?

Darwin 23.4.0 arm64 arm

What steps can reproduce the bug?

.mapResponse behaves differently depending on whether it's invoked before or after other methods. This is based on the mapResponse test here

Case 1

mapResponse before the method handler will map the response.

it('work global', async () => {
  const app = new Elysia()
    .mapResponse(() => new Response('A'))
    .get('/', (context) => context.error(401))

  const res = await app.handle(req('/')).then((x) => x.text())

  expect(res).toBe('A')
})

Case 2

mapResponse after the request handler will not map the response (the route returns an error).

it('work global', async () => {
  const app = new Elysia()
    .get('/', (context) => context.error(401))
    .mapResponse(() => new Response('A'))

  const res = await app.handle(req('/')).then((x) => x.text())

  expect(res).toBe('A')
})

Case 3

Same as case 1, but for some reason printing out the context will mean the response is not mapped.

it('work global', async () => {
  const app = new Elysia()
   .mapResponse((context) => {
      console.log(context)
      return new Response('A')
    )
    .get('/', (context) => context.error(401))

  const res = await app.handle(req('/')).then((x) => x.text())

  expect(res).toBe('A')
})

What is the expected behavior?

mapResponse should only be called on valid, non-error responses, regardless of where it's invoked.

What do you see instead?

mapResponse is sometimes called when there are errors.

Additional information

No response

Have you try removing the node_modules and bun.lockb and try again yet?

Yes