README
✨ tRPC-transformer
A simple, quick and reliable transformer for tRPC based on:
Installation
yarn add trpc-transformer
or
npm i trpc-transformer
Usage
- Add it to your
AppRouter:
import transformer from 'trpc-transformer';
const appRouter = trpc.router().transformer(transformer);
// .query(...)
- ...and to your tRPC client:
import transformer from 'trpc-transformer';
const client = createTRPCClient<AppRouter>({
// [...]
transformer,
});
Benefits
Assuming you have appRouter.ts on the server-side:
import * as trpc from '@trpc/server';
import transformer from 'trpc-transformer';
import * as yup from 'yup';
import DB from '../lib/your-persistence-layer';
export const appRouter = trpc
.router()
.transformer(transformer)
.mutation('createUser', {
input: yup
.object({
name: yup.string().min(5).required(),
birthDate: yup.date().required(),
})
.required(),
async resolve({ input: { name } }) {
const user: {
id: number;
name: string;
createdAt: Date;
} = await DB.users.create({ name });
return user;
},
});
export type AppRouter = typeof appRouter;
...then, on the client you'll have your data correctly serialized/deserialized:
import * as trpc from '@trpc/client';
import transformer from 'trpc-transformer';
import type { Router } from '../appRouter.ts';
const client = trpc.createTRPCClient<Router>({ url: '/trpc', transformer });
// ...
const user = await client.mutation('createUser', {
name: 'John Doe',
birthDate: new Date('1980-06-25'),
});
console.log(user.createdAt instanceof Date); // true
Why this exists
So you don't have to do this every time:
import devalue from 'devalue';
import superjson from 'superjson';
const transformer = {
input: superjson,
output: {
serialize: (object: unknown) => devalue(object),
deserialize: (object: unknown) => eval(`(${object})`),
},
};
Learn more
See trpc.io/docs/data-transformers and github.com/blitz-js/superjson.
License
The ISC License.