JSPM

  • Created
  • Published
  • Downloads 1577
  • Score
    100M100P100Q137458F
  • License ISC

Simple tRPC transformer based on superjson with Decimal.js support

Package Exports

  • trpc-transformer
  • trpc-transformer/dist/index.cjs
  • trpc-transformer/dist/index.mjs

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (trpc-transformer) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

✨ tRPC-transformer

NPM version License Downloads Sponsor the author

A simple tRPC transformer based on superjson with Decimal.js support.

Installation

yarn add trpc-transformer

or

npm i trpc-transformer

Usage

  1. Add it to your AppRouter:
import transformer from 'trpc-transformer';

const appRouter = trpc.router().transformer(transformer);
// .query(...)
  1. ...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

Learn more

See trpc.io/docs/data-transformers and github.com/blitz-js/superjson.

License

The ISC License.