Skip to content

Instantly share code, notes, and snippets.

@jaysson
Last active March 23, 2024 20:31
Show Gist options
  • Save jaysson/c2fffcd8539d57105e524b51cd38fce7 to your computer and use it in GitHub Desktop.
Save jaysson/c2fffcd8539d57105e524b51cd38fce7 to your computer and use it in GitHub Desktop.
TRPC Integration for Adonis
import Route from '@ioc:Adonis/Core/Route';
import { handleHttpRequest } from 'App/TRPC';
Route.any('/trpc/*', handleHttpRequest);
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
Copy link

ThBM commented Feb 1, 2023

Thanks for sharing!

I would modify the t initialization for type inference of HttpContextContract.

const t = initTRPC.context<HttpContextContract>().create();

@vinicioslc
Copy link

@ThBM oh this is nice thanks !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment