Saltar al contenido principal
Versión: 9.x

Inicio rápido

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 →

consejo

Te recomendamos encarecidamente explorar las aplicaciones de ejemplo para familiarizarte con tRPC y comenzar a trabajar de la manera más fluida posible.

Instalación

⚠️ Requisitos: tRPC requiere TypeScript > 4.1 ya que depende de Template Literal Types.

npm install @trpc/server

Para implementar endpoints y routers de tRPC. Instálalo en tu código base del servidor.

npm install @trpc/client @trpc/server

Para realizar llamadas API tipadas desde tu cliente. Instálalo en tu base de código cliente (@trpc/server es una dependencia peer de @trpc/client).

npm install @trpc/react react-query@3

Para generar un potente conjunto de hooks React que consulten tu API tRPC. Basado en react-query.

npm install @trpc/next

Conjunto de utilidades para integrar tRPC con Next.js.

Fragmentos de instalación

npm:

bash
npm install @trpc/server @trpc/client @trpc/react react-query@3 @trpc/next
bash
npm install @trpc/server @trpc/client @trpc/react react-query@3 @trpc/next

yarn:

bash
yarn add @trpc/server @trpc/client @trpc/react react-query@3 @trpc/next
bash
yarn add @trpc/server @trpc/client @trpc/react react-query@3 @trpc/next

Definir un router

Exploraremos los pasos para construir una API tipada con tRPC. Inicialmente, esta API contendrá solo dos endpoints:

ts
getUser(id: string) => { id: string; name: string; }
createUser(data: {name:string}) => { id: string; name: string; }
ts
getUser(id: string) => { id: string; name: string; }
createUser(data: {name:string}) => { id: string; name: string; }

Crear una instancia de router

Primero definimos un router en algún lugar de nuestro código base del servidor:

server.ts
ts
import * as trpc from '@trpc/server';
const appRouter = trpc.router();
// only export *type signature* of router!
// to avoid accidentally importing your API
// into client-side code
export type AppRouter = typeof appRouter;
server.ts
ts
import * as trpc from '@trpc/server';
const appRouter = trpc.router();
// only export *type signature* of router!
// to avoid accidentally importing your API
// into client-side code
export type AppRouter = typeof appRouter;

Añadir un endpoint query

Usa el método .query() para añadir un endpoint query al router. Argumentos:

.query(name: string, params: QueryParams)

  • name: string: Nombre de este endpoint

  • params.input: Opcional. Función que valida/convierte el input de este endpoint y retorna un valor fuertemente tipado (si es válido) o lanza un error (si no lo es). Alternativamente puedes pasar un esquema de Zod, Superstruct o Yup.

  • params.resolve: Implementación real del endpoint. Función con un único argumento req. El input validado está en req.input y el contexto en req.ctx (¡más sobre esto después!)

server.ts
ts
import * as trpc from '@trpc/server';
const appRouter = trpc.router().query('getUser', {
input: (val: unknown) => {
if (typeof val === 'string') return val;
throw new Error(`Invalid input: ${typeof val}`);
},
async resolve(req) {
req.input; // string
return { id: req.input, name: 'Bilbo' };
},
});
export type AppRouter = typeof appRouter;
server.ts
ts
import * as trpc from '@trpc/server';
const appRouter = trpc.router().query('getUser', {
input: (val: unknown) => {
if (typeof val === 'string') return val;
throw new Error(`Invalid input: ${typeof val}`);
},
async resolve(req) {
req.input; // string
return { id: req.input, name: 'Bilbo' };
},
});
export type AppRouter = typeof appRouter;

Añadir un endpoint mutation

Similar a GraphQL, tRPC distingue entre endpoints query y mutation. Añadamos una mutation createUser:

ts
createUser(payload: {name: string}) => {id: string; name: string};
ts
createUser(payload: {name: string}) => {id: string; name: string};
server.ts
ts
import * as trpc from '@trpc/server';
import { z } from 'zod';
const appRouter = trpc
.router()
.query('getUser', {
input: (val: unknown) => {
if (typeof val === 'string') return val;
throw new Error(`Invalid input: ${typeof val}`);
},
async resolve(req) {
req.input; // string
return { id: req.input, name: 'Bilbo' };
},
})
.mutation('createUser', {
// validate input with Zod
input: z.object({ name: z.string().min(5) }),
async resolve(req) {
// use your ORM of choice
return await UserModel.create({
data: req.input,
});
},
});
export type AppRouter = typeof appRouter;
server.ts
ts
import * as trpc from '@trpc/server';
import { z } from 'zod';
const appRouter = trpc
.router()
.query('getUser', {
input: (val: unknown) => {
if (typeof val === 'string') return val;
throw new Error(`Invalid input: ${typeof val}`);
},
async resolve(req) {
req.input; // string
return { id: req.input, name: 'Bilbo' };
},
})
.mutation('createUser', {
// validate input with Zod
input: z.object({ name: z.string().min(5) }),
async resolve(req) {
// use your ORM of choice
return await UserModel.create({
data: req.input,
});
},
});
export type AppRouter = typeof appRouter;

Próximos pasos

tRPC incluye herramientas más sofisticadas para el cliente, diseñadas específicamente para proyectos React y Next.js. Continúa con las guías adecuadas: