- Published on
tRPC
- Authors
- Name
- Shelton Ma
1. tRPC for fastify
install
pnpm add @trpc/server zod pnpm add -D @trpc/server/adapters/fastify
create
src/trpc.ts
import { initTRPC } from '@trpc/server'; import { z } from 'zod'; const t = initTRPC.create(); export const appRouter = t.router({ hello: t.procedure .input(z.object({ name: z.string() })) .query(({ input }) => { return { greeting: `Hello, ${input.name}!` }; }), }); export type AppRouter = typeof appRouter;
in
src/index.ts
import { fastifyTRPCPlugin } from '@trpc/server/adapters/fastify'; import { appRouter } from './trpc'; await fastify.register(fastifyTRPCPlugin, { prefix: '/trpc', trpcOptions: { router: appRouter, createContext: () => ({}) }, });
2. tRPC for package
package/trpc/router.ts
import { initTRPC } from '@trpc/server'; import { z } from 'zod'; const t = initTRPC.create(); export const appRouter = t.router({ hello: t.procedure .input(z.object({ name: z.string() })) .query(({ input }) => { return { greeting: `Hello, ${input.name}!` }; }), }); // Export type definition export type AppRouter = typeof appRouter;
export approuter in
index.ts
export * from './router';
Usage in Fastify App (
apps/api/src/index.ts
)import Fastify from 'fastify'; import { fastifyTRPCPlugin } from '@trpc/server/adapters/fastify'; import { appRouter } from 'package/trpc'; const fastify = Fastify({ logger: true }); await fastify.register(fastifyTRPCPlugin, { prefix: '/trpc', trpcOptions: { router: appRouter, createContext: () => ({}), }, }); fastify.listen({ port: 3000 });
aliase path
// tsconfig.json { "compilerOptions": { "baseUrl": ".", "paths": { "package/trpc": ["package/trpc/index.ts"] } } }
Use in each sub-project (apps/api/tsconfig.json)
{ "extends": "../../tsconfig.json", "compilerOptions": { "outDir": "dist", "rootDir": "src" }, "include": ["src"] }