Saltar al contenido principal
Versión: 9.x

Definir Router

Traducción Beta No Oficial

Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →

información
  • Un procedimiento puede considerarse el equivalente a un endpoint REST.
  • No hay diferencia interna entre consultas (queries) y mutaciones, más allá de la semántica.
  • Definir un router funciona igual para consultas, mutaciones y suscripciones, excepto que las suscripciones deben retornar una instancia de Subscription.

Validación de entrada

tRPC funciona inmediatamente con validadores como yup/superstruct/zod/myzod/personalizados/etc. - ver suite de pruebas

Ejemplo sin entrada

tsx
import * as trpc from '@trpc/server';
// [...]
export const appRouter = trpc
.router<Context>()
// Create procedure at path 'hello'
.query('hello', {
resolve({ ctx }) {
return {
greeting: `hello world`,
};
},
});
tsx
import * as trpc from '@trpc/server';
// [...]
export const appRouter = trpc
.router<Context>()
// Create procedure at path 'hello'
.query('hello', {
resolve({ ctx }) {
return {
greeting: `hello world`,
};
},
});

Con Zod

tsx
import * as trpc from '@trpc/server';
import { z } from 'zod';
// [...]
export const appRouter = trpc.router<Context>().query('hello', {
input: z
.object({
text: z.string().nullish(),
})
.nullish(),
resolve({ input }) {
return {
greeting: `hello ${input?.text ?? 'world'}`,
};
},
});
export type AppRouter = typeof appRouter;
tsx
import * as trpc from '@trpc/server';
import { z } from 'zod';
// [...]
export const appRouter = trpc.router<Context>().query('hello', {
input: z
.object({
text: z.string().nullish(),
})
.nullish(),
resolve({ input }) {
return {
greeting: `hello ${input?.text ?? 'world'}`,
};
},
});
export type AppRouter = typeof appRouter;

Con Yup

tsx
import * as trpc from '@trpc/server';
import * as yup from 'yup';
// [...]
export const appRouter = trpc.router<Context>().query('hello', {
input: yup.object({
text: yup.string().required(),
}),
resolve({ input }) {
return {
greeting: `hello ${input?.text ?? 'world'}`,
};
},
});
export type AppRouter = typeof appRouter;
tsx
import * as trpc from '@trpc/server';
import * as yup from 'yup';
// [...]
export const appRouter = trpc.router<Context>().query('hello', {
input: yup.object({
text: yup.string().required(),
}),
resolve({ input }) {
return {
greeting: `hello ${input?.text ?? 'world'}`,
};
},
});
export type AppRouter = typeof appRouter;

Con Superstruct

tsx
import * as trpc from '@trpc/server';
import * as t from 'superstruct';
// [...]
export const appRouter = trpc.router<Context>().query('hello', {
input: t.object({
/**
* Also supports inline doc strings when referencing the type.
*/
text: t.defaulted(t.string(), 'world'),
}),
resolve({ input }) {
return {
greeting: `hello ${input.text}`,
};
},
});
export type AppRouter = typeof appRouter;
tsx
import * as trpc from '@trpc/server';
import * as t from 'superstruct';
// [...]
export const appRouter = trpc.router<Context>().query('hello', {
input: t.object({
/**
* Also supports inline doc strings when referencing the type.
*/
text: t.defaulted(t.string(), 'world'),
}),
resolve({ input }) {
return {
greeting: `hello ${input.text}`,
};
},
});
export type AppRouter = typeof appRouter;

Encadenamiento de métodos

Para agregar múltiples endpoints, debes encadenar las llamadas

tsx
import * as trpc from '@trpc/server';
// [...]
export const appRouter = trpc
.router<Context>()
.query('hello', {
resolve() {
return {
text: `hello world`,
};
},
})
.query('bye', {
resolve() {
return {
text: `goodbye`,
};
},
});
export type AppRouter = typeof appRouter;
tsx
import * as trpc from '@trpc/server';
// [...]
export const appRouter = trpc
.router<Context>()
.query('hello', {
resolve() {
return {
text: `hello world`,
};
},
})
.query('bye', {
resolve() {
return {
text: `goodbye`,
};
},
});
export type AppRouter = typeof appRouter;