elysiajs / elysia

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

onResponse handler neither has the response object nor the Request socket object available (TS) #324

Open otherguy opened 11 months ago

otherguy commented 11 months ago

Creating a new issue since #190 was closed.

Unfortunately, the onResponse handler can neither access the actual Response object (to get e.g. response length) nor does it have access to the underlying socket, to get the request protocol for example.

Would it be possible to get the Response object inside the context of the onResponse handler? And an access to req.socket in the TypeScript Request object?

Responding to

In 0.7.0, you should be able to access Response in afterHandle as the following.

new Elysia()
  .onAfterHandle(({ response }) => {
})

Originally posted by @SaltyAom in https://github.com/elysiajs/elysia/issues/190#issuecomment-1813985800

Using elysia@0.7.29, in a minimal example, when used as a middleware, response is undefined.

What I would want is to get the response object (to get the response size) in either onAfterHandle or, preferably, onResponse.

Similarly, in onResponse, it would be great to have access to ctx.request.socket to get the original request protocol.

return app
  .derive((ctx) => {
    return {
      ip: String(getIP(ctx.request.headers))
    };
  })
  .onError((ctx) => {
    ctx.store = { error: ctx.error, ...ctx.store };
  })
  .onRequest((ctx) => {
    ctx.store = { requestStart: process.hrtime.bigint(), ...ctx.store };
  })
  .onAfterHandle(({response}) => {
    console.log(response);
  })
  .onResponse((ctx) => {
  })
otherguy commented 1 month ago

@SaltyAom any progress on this one?

SaltyAom commented 1 month ago

If I understand correctly, you want to get both request, and response on onAfterResponse (previously 'onResponse').

onAfterResponse include response by default since name change or since 1.1.

new Elysia()
    .derive(({ server, request }) => {
        return {
            ip: String(server?.requestIP(request))
        }
    })
    .onError((ctx) => {
        ctx.store = { error: ctx.error, ...ctx.store }
    })
    .onRequest((ctx) => {
        ctx.store = { requestStart: process.hrtime.bigint(), ...ctx.store }
    })
    .onAfterResponse(({ request, response }) => {
        console.log({
            request,
            response
        })
    })
    .get('/', () => 'a')
    .listen(3000)