Saltar al contenido principal
Versión: 9.x

Validación de Salida

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 →

tRPC te ofrece seguridad de tipos automática en las salidas sin necesidad de agregar un validador; sin embargo, en ocasiones puede ser útil definir estrictamente el tipo de salida para evitar la filtración de datos sensibles.

Similar a input:, puedes agregar una validación output: a los métodos de router query() y mutation(). El validador de salida se invoca con la carga útil devuelta por la función resolve().

Cuando se define un validador de output, su tipo inferido se espera como tipo de retorno de la función resolve().

información
  • Esto es completamente opcional y solo si deseas asegurarte de no filtrar accidentalmente nada
  • Si falla la validación de salida, el servidor responderá con un INTERNAL_SERVER_ERROR.

Ejemplos

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

Con Zod

tsx
import * as trpc from '@trpc/server';
import { z } from 'zod';
// [...]
export const appRouter = trpc.router<Context>().query('hello', {
output: z.object({
greeting: z.string(),
}),
// expects return type of { greeting: string }
resolve() {
return {
greeting: 'hello!',
};
},
});
export type AppRouter = typeof appRouter;
tsx
import * as trpc from '@trpc/server';
import { z } from 'zod';
// [...]
export const appRouter = trpc.router<Context>().query('hello', {
output: z.object({
greeting: z.string(),
}),
// expects return type of { greeting: string }
resolve() {
return {
greeting: 'hello!',
};
},
});
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', {
output: yup.object({
greeting: yup.string().required(),
}),
resolve() {
return { greeting: 'hello!' };
},
});
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', {
output: yup.object({
greeting: yup.string().required(),
}),
resolve() {
return { greeting: 'hello!' };
},
});
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.string(),
output: t.object({
greeting: t.string(),
}),
resolve({ input }) {
return { greeting: input };
},
});
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.string(),
output: t.object({
greeting: t.string(),
}),
resolve({ input }) {
return { greeting: input };
},
});
export type AppRouter = typeof appRouter;

Con validador personalizado

tsx
import * as trpc from '@trpc/server';
import * as t from 'superstruct';
// [...]
export const appRouter = trpc.router<Context>().query('hello', {
output: (value: any) => {
if (value && typeof value.greeting === 'string') {
return { greeting: value.greeting };
}
throw new Error('Greeting not found');
},
// expects return type of { greeting: string }
resolve() {
return { greeting: 'hello!' };
},
});
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', {
output: (value: any) => {
if (value && typeof value.greeting === 'string') {
return { greeting: value.greeting };
}
throw new Error('Greeting not found');
},
// expects return type of { greeting: string }
resolve() {
return { greeting: 'hello!' };
},
});
export type AppRouter = typeof appRouter;