Last active
October 29, 2024 11:02
-
-
Save jaysson/c2fffcd8539d57105e524b51cd38fce7 to your computer and use it in GitHub Desktop.
TRPC Integration for Adonis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Route from '@ioc:Adonis/Core/Route'; | |
import { handleHttpRequest } from 'App/TRPC'; | |
Route.any('/trpc/*', handleHttpRequest); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { initTRPC } from '@trpc/server'; | |
import { resolveHTTPResponse } from '@trpc/server/http'; | |
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; | |
const t = initTRPC.create(); | |
export const appRouter = t.router({ | |
hello: t.procedure.query(() => { | |
return { message: 'World' }; | |
}), | |
}); | |
export const handleHttpRequest = async (ctx: HttpContextContract) => { | |
const { request, response } = ctx; | |
const url = new URL(request.completeUrl(true)); | |
const path = url.pathname.slice('/trpc'.length + 1); | |
const { body, status, headers } = await resolveHTTPResponse({ | |
createContext: async () => ctx, | |
router: appRouter, | |
path, | |
req: { | |
query: url.searchParams, | |
method: request.method(), | |
headers: request.headers(), | |
body: request.body(), | |
}, | |
}); | |
if (headers) { | |
Object.keys(headers).forEach((key) => { | |
const value = headers[key]; | |
if (value) response.header(key, value); | |
}); | |
} | |
response.status(status); | |
response.send(body); | |
} | |
export type AppRouter = typeof appRouter; |
@ThBM oh this is nice thanks !
for tRPC ^11.0.0-rc.593 / Adonis.js v5
import { fetchRequestHandler } from '@trpc/server/adapters/fetch'
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
export const handleHttpRequest = async (ctx: HttpContextContract) => {
const { request, response } = ctx
const result = await fetchRequestHandler({
endpoint: '/trpc',
req: new Request(request.completeUrl(true), {
headers: request.headers(),
body: request.method() !== 'GET' ? JSON.stringify(request.body()) : undefined,
method: request.method()
}),
router: createRouter(),
createContext: async () => ctx
})
const responseText = await new Response(result.body).text()
return response.status(result.status).header('content-type', 'application/json').send(responseText)
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing!
I would modify the
t
initialization for type inference of HttpContextContract.const t = initTRPC.context<HttpContextContract>().create();