elysiajs / elysia

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

Ability to rewrite an incoming request's url or have a prefix that's not actually added to the path? #510

Closed SelfhostedPro closed 2 weeks ago

SelfhostedPro commented 6 months ago

What is the problem this feature would solve?

Is there a way to rewrite an incoming request's url? I'm working on a project using hono and vite to render and serve a frontend (vue with ssr).

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

There's a vite plugin for hono as a devserver already so I wanted to see about using it for the initial server (server.ts) and mounting elysia to /api inside of that. Unfortunately, it already gets /api applied as a prefix outside of elysia and it doesn't seem like there's a good way to tell it that so even though an endpoint is served at /api/hello elysia will just think it's served at /hello.

Here is where the mount happens: https://github.com/SelfhostedPro/hono-vue-vite-ssr/blob/936c8907bca2204193c3aca3a16169af2bb559b3/server.ts#L47

Here is where I'm creating my elysia instance: https://github.com/SelfhostedPro/hono-vue-vite-ssr/blob/main/src/api/index.ts (where adding the prefix would cause the path to be /api/api/ instead of /api)

What alternatives have you considered?

If there's already a way to do this, I haven't seen documentation for it. I tried creating a new request in an onRequest hook and a transform hook with no luck (and also a terrible dx).

    .onRequest(async ({ request }) => {
        console.log(request.url)
        request = new Request(
            new URL((request.url.split('/').slice(0, 3).join('') + '/api/' + (request.url.split('/')[4] ? request.url.split('/')[4] : '')))
        )
        console.log(request.url)
    })

I can see if hono provides a way to specify this but I don't see docs for much around mount over there either.

SaltyAom commented 2 weeks ago

Elysia context is not readonly, you can override it like normal JavaScript object.

new Elysia()
    .onRequest((context) => {
        context.request = new Request(
            new URL((request.url.split('/').slice(0, 3).join('') + '/api/' + (request.url.split('/')[4] ? request.url.split('/')[4] : '')))
        )
        console.log(request.url)
    })

Closing as complete.