Last active
March 23, 2024 20:31
-
-
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; |
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();