Published on

tRPC

Authors
  • avatar
    Name
    Shelton Ma
    Twitter

1. tRPC for fastify

  1. install

    pnpm add @trpc/server zod
    pnpm add -D @trpc/server/adapters/fastify
    
  2. 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;
    
  3. 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

  1. 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;
    
  2. export approuter in index.ts

    export * from './router';
    
  3. 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 });
    
  4. aliase path

    // tsconfig.json
    {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "package/trpc": ["package/trpc/index.ts"]
        }
      }
    }
    
  5. Use in each sub-project (apps/api/tsconfig.json)

    {
      "extends": "../../tsconfig.json",
      "compilerOptions": {
        "outDir": "dist",
        "rootDir": "src"
      },
      "include": ["src"]
    }