elysiajs / elysia

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

Add `response` object in route handlers arguments as an alternative to `set` and `cookie` #715

Open remorses opened 1 month ago

remorses commented 1 month ago

What is the problem this feature would solve?

Currently setting headers and cookies is a bit weird in my opinion:

new Elysia().post('/mirror', async ({ cookie, set }) => {
    set.headers['x-powered-by'] = 'Elysia'
    cookie.x.set({ value: '123' })
})

I already have utility functions and libraries that relies on the Response and Headers objects instead of these new Proxy based APIs.

What is the feature you are proposing to solve the problem?

I propose adding a response stub of type Response in the handler arguments, this way setting cookies and headers is easier if you already know that API.

new Elysia()
    .onRequest(({ response }) => {
        response.headers.set('x-powered-by', 'Elysia')
    })
    .post('/mirror', async ({ response }) => {
        response.headers.set('set-cookie', 'x=123')
    })

What alternatives have you considered?

You could also return a Response manually with the headers set. The problem is that sometimes an handler requires setting some headers always and you can forget returning the response with the headers set.

new Elysia().post('/mirror', async ({}) => {
    const response = new Response()
    response.headers.set('x-powered-by', 'Elysia')

    if (something) {
        // headers are not set here, easy to forget
        return {
            something: 'else',
        }
    }

    return response
})