Към всички skills

adapter-fastify

trpc · DevOps

Mount tRPC as a Fastify plugin with fastifyTRPCPlugin from @trpc/server/adapters/fastify. Configure prefix, trpcOptions (router, createContext, onError). Enable WebSocket subscriptions with useWSS and @fastify/websocket. Set routerOptions.maxParamLength for batch requests. Requires Fastify v5+. Fast

Оригинален текст · няма потвърден превод на български

Първо прочетете инструкцията.

Файлът се зарежда от посочения източник само по ваше действие. Можете да го прочетете тук, да го копирате или да го запазите като .md.

Оригинален SKILL.md
GitHub хранилище
Звезди на репото
40 315
Лиценз
Не е посочен. Проверете в репозитория.
Последна проверка на записа
Няма посочена дата

Добавете в своя инструмент.

Командата отваря избора на skills от репозитория. Прочетете файла и условията на автора преди изпълнение.

npx skills add trpc/trpc

Страницата копира текст. Не инсталира и не изпълнява нищо на устройството ви.

Откъс от SKILL.md

Началото на файла на автора, без превод.

tRPC — Adapter: Fastify

Setup

// server.ts
import { initTRPC } from '@trpc/server';
import {
  fastifyTRPCPlugin,
  FastifyTRPCPluginOptions,
} from '@trpc/server/adapters/fastify';
import type { CreateFastifyContextOptions } from '@trpc/server/adapters/fastify';
import fastify from 'fastify';
import { z } from 'zod';

function createContext({ req, res }: CreateFastifyContextOptions) {
  return { req, res };
}
type Context = Awaited<ReturnType<typeof createContext>>;

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

const appRouter = t.router({
  greet: t.procedure
    .input(z.object({ name: z.string() }))
    .query(({ input }) => ({ greeting: `Hello, ${input.name}!` })),
});

export type AppRouter = typeof appRouter;

const server = fastify({
  routerOptions: {
    maxParamLength: 5000,
  },
});

server.register(fastifyTRPCPlugin, {
  prefix: '/trpc',
  trpcOptions: {
    router: appRouter,
    createContext,
    onError({ path, error }) {
      console.error(`Error in tRPC handler on path '${path}':`, error);
    },
  } satisfies FastifyTRPCPluginOptions<AppRouter>['trpcOptions'],
});

(async () => {
  try {
    await server.listen({ port: 3000 });
    console.log('Listening on http://localhost:3000');
  } catch (err) {
    server.log.error(err);
    process.exit(1);
  }
})();

Core Patterns

WebSocket subscriptions with @fastify/websocket

import ws from '@fastify/websocket';
import {
  fastifyTRPCPlugin,
  FastifyTRPCPluginOptions,
} from '@trpc/server/adapters/fastify';
import fastify from 'fastify';
import { createContext } from './context';
import { appRouter, type AppRouter } from './router';

const server = fastify({
  routerOptions: { maxParamLength: 5000 },
});

// Register @fastify/websocket BEFORE the tRPC plugin
server.register(ws);

server.register(fastifyTRPCPlugin, {
  prefix: '/trpc',
  useWSS: true,
  trpcOptions: {
    router: appRouter,
    createContext,
    keepAlive: {
      enabled: true,
      pingMs: 30000,
      pongWaitMs: 5000,
    },
  } satisfies FastifyTRPCPluginOptions<AppRouter>['trpcOptions'],
});

server.listen({ port: 3000 });

Install: npm install @fastify/websocket (minimum version 3.11.0)

Type-safe onError with satisfies

Целият SKILL.md в GitHub