Files
trpc-nuxt/README.md
Robert Soriano 5d8d49c345 update readme
2022-05-18 00:03:54 -07:00

2.0 KiB

tRPC-Nuxt

Version

End-to-end typesafe APIs with tRPC.io in Nuxt applications.

Install

npm i trpc-nuxt -D
// nuxt.config.ts
import { defineNuxtConfig } from 'nuxt'

export default defineNuxtConfig({
  modules: ['trpc-nuxt'],
})

Usage

Create your tRPC routes and context under ~/server/trpc/index.ts:

// ~/trpc/index.ts
import type { inferAsyncReturnType } from '@trpc/server'
import * as trpc from '@trpc/server'

export const router = trpc
  .router<inferAsyncReturnType<typeof createContext>>()
  // queries and mutations...
  .query('hello', {
    resolve: () => 'world',
  })
  .query('bye', {
    resolve() {
      return {
        text: 'goodbye',
      }
    },
  })

// optional
export const createContext = () => {
  // ...
  return {
    /** context data */
  }
}

// optional
export const responseMeta = () => {
  // ...
  return {
    // { headers: ... }
  }
}

Use the client like so:

<script setup lang="ts">
const client = useClient()

const greeting = await client.query('hello');
console.log(greeting); // => 👈 world

const farewell = await client.query('bye');
console.log(farewell); // => 👈 goodbye
</script>

Recipes

Input validation with Zod

tRPC works out-of-the-box with yup/superstruct/zod/myzod/custom validators. Learn more about input validation here.

// ~/server/trpc/index.ts
import { z } from 'zod'

export const router = trpc
  .router()
  .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,
      })
    },
  })

Learn more about tRPC.io here.

License

MIT