Saltar al contenido principal
Versión: 10.x

Transformadores de Datos

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 →

Puedes serializar los datos de respuesta y los argumentos de entrada. Los transformadores deben agregarse tanto en el servidor como en el cliente.

Uso de superjson​

SuperJSON nos permite usar transparentemente tipos estándar como Date, Map o Set en la comunicación entre el servidor y el cliente. Es decir, puedes devolver cualquiera de estos tipos desde tu API-resolver y utilizarlos directamente en el cliente sin necesidad de reconstruir los objetos desde JSON.

Cómo hacerlo​

1. Instalar​

bash
yarn add superjson
bash
yarn add superjson

2. Agregar a tu initTRPC​

routers/router/_app.ts
ts
import { initTRPC } from '@trpc/server';
import superjson from 'superjson';
export const t = initTRPC.create({
transformer: superjson,
});
routers/router/_app.ts
ts
import { initTRPC } from '@trpc/server';
import superjson from 'superjson';
export const t = initTRPC.create({
transformer: superjson,
});

3. Agregar a createTRPCProxyClient() o createTRPCNext()​

ts
import { createTRPCProxyClient } from '@trpc/client';
import type { AppRouter } from '~/server/routers/_app';
import superjson from 'superjson';
export const client = createTRPCProxyClient<AppRouter>({
transformer: superjson, // <--
// [...]
});
ts
import { createTRPCProxyClient } from '@trpc/client';
import type { AppRouter } from '~/server/routers/_app';
import superjson from 'superjson';
export const client = createTRPCProxyClient<AppRouter>({
transformer: superjson, // <--
// [...]
});
utils/trpc.ts
ts
import { createTRPCNext } from '@trpc/next';
import type { AppRouter } from '~/server/routers/_app';
import superjson from 'superjson';
// [...]
export const trpc = createTRPCNext<AppRouter>({
config(config) {
return {
transformer: superjson, // <--
};
},
// [...]
});
utils/trpc.ts
ts
import { createTRPCNext } from '@trpc/next';
import type { AppRouter } from '~/server/routers/_app';
import superjson from 'superjson';
// [...]
export const trpc = createTRPCNext<AppRouter>({
config(config) {
return {
transformer: superjson, // <--
};
},
// [...]
});

Transformadores diferentes para subida y descarga​

Si necesitas usar un transformador solo en una dirección o diferentes transformadores para subida y descarga (por ejemplo, por razones de rendimiento), puedes proporcionar transformadores individuales. Asegúrate de usar el mismo transformador combinado en todas partes.

Cómo hacerlo​

Aquí se usa superjson para la subida de datos y devalue para la descarga, porque devalue es mucho más rápido pero inseguro para usar en el servidor.

1. Instalar​

bash
yarn add superjson devalue
bash
yarn add superjson devalue

2. Agregar a utils/trpc.ts​

utils/trpc.ts
ts
import { uneval } from 'devalue';
import superjson from 'superjson';
// [...]
export const transformer = {
input: superjson,
output: {
serialize: (object) => uneval(object),
// This `eval` only ever happens on the **client**.
deserialize: (object) => (0, eval)(`(${object})`),
},
};
utils/trpc.ts
ts
import { uneval } from 'devalue';
import superjson from 'superjson';
// [...]
export const transformer = {
input: superjson,
output: {
serialize: (object) => uneval(object),
// This `eval` only ever happens on the **client**.
deserialize: (object) => (0, eval)(`(${object})`),
},
};

3. Agregar a tu AppRouter​

server/routers/_app.ts
ts
import { initTRPC } from '@trpc/server';
import { transformer } from '../../utils/trpc';
export const t = initTRPC.create({
transformer,
});
export const appRouter = t.router({
// [...]
});
server/routers/_app.ts
ts
import { initTRPC } from '@trpc/server';
import { transformer } from '../../utils/trpc';
export const t = initTRPC.create({
transformer,
});
export const appRouter = t.router({
// [...]
});

4. Agregar a createTRPCProxyClient()​

client.ts
ts
import { createTRPCProxyClient } from '@trpc/client';
import { transformer } from '../utils/trpc';
export const client = createTRPCProxyClient<AppRouter>({
transformer, // <--
// [...]
});
client.ts
ts
import { createTRPCProxyClient } from '@trpc/client';
import { transformer } from '../utils/trpc';
export const client = createTRPCProxyClient<AppRouter>({
transformer, // <--
// [...]
});

Interfaz DataTransformer​

ts
export interface DataTransformer {
serialize(object: any): any;
deserialize(object: any): any;
}
interface InputDataTransformer extends DataTransformer {
/**
* This function runs **on the client** before sending the data to the server.
*/
serialize(object: any): any;
/**
* This function runs **on the server** to transform the data before it is passed to the resolver
*/
deserialize(object: any): any;
}
interface OutputDataTransformer extends DataTransformer {
/**
* This function runs **on the server** before sending the data to the client.
*/
serialize(object: any): any;
/**
* This function runs **only on the client** to transform the data sent from the server.
*/
deserialize(object: any): any;
}
export interface CombinedDataTransformer {
/**
* Specify how the data sent from the client to the server should be transformed.
*/
input: InputDataTransformer;
/**
* Specify how the data sent from the server to the client should be transformed.
*/
output: OutputDataTransformer;
}
ts
export interface DataTransformer {
serialize(object: any): any;
deserialize(object: any): any;
}
interface InputDataTransformer extends DataTransformer {
/**
* This function runs **on the client** before sending the data to the server.
*/
serialize(object: any): any;
/**
* This function runs **on the server** to transform the data before it is passed to the resolver
*/
deserialize(object: any): any;
}
interface OutputDataTransformer extends DataTransformer {
/**
* This function runs **on the server** before sending the data to the client.
*/
serialize(object: any): any;
/**
* This function runs **only on the client** to transform the data sent from the server.
*/
deserialize(object: any): any;
}
export interface CombinedDataTransformer {
/**
* Specify how the data sent from the client to the server should be transformed.
*/
input: InputDataTransformer;
/**
* Specify how the data sent from the server to the client should be transformed.
*/
output: OutputDataTransformer;
}