Skip to content

Instantly share code, notes, and snippets.

@jaysson
Last active October 29, 2024 11:02
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 !

@xferqr
Copy link

xferqr commented Oct 29, 2024

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