From 5bd43a54e5a8b1fe0e5d404b3414d9a3da4df878 Mon Sep 17 00:00:00 2001 From: Robert Soriano Date: Wed, 18 May 2022 09:29:47 -0700 Subject: [PATCH] update validation readme --- recipes/authorization.md | 54 +++++++++++++++++++++++++++++++++++++--- recipes/validation.md | 4 ++- 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/recipes/authorization.md b/recipes/authorization.md index 629bb72..ccdeb4c 100644 --- a/recipes/authorization.md +++ b/recipes/authorization.md @@ -1,10 +1,12 @@ ## Authorization -The `createContext`-function is called for each incoming request so here you can add contextual information about the calling user from the request object. Learn more about authorization [here](https://trpc.io/docs/authorization). +The `createContext`-function is called for each incoming request so here you can add contextual information about the calling user from the request object. + +## Create context from request headers ```ts // ~/server/trpc/index.ts -import * as trpc from '@trpc/server' +import type * as trpc from '@trpc/server' import type { CompatibilityEvent } from 'h3' import { decodeAndVerifyJwtToken } from '~/somewhere/in/your/app/utils' @@ -28,8 +30,16 @@ export async function createContext({ req }: CompatibilityEvent) { } } +type Context = trpc.inferAsyncReturnType + +// [..] Define API handler and app router +``` + +## Option 1: Authorize using resolver + +```ts export const router = trpc - .router>() + .router() // open for anyone .query('hello', { input: z.string().nullish(), @@ -49,3 +59,41 @@ export const router = trpc }, }) ``` + +## Option 2: Authorize using middleware + +```ts +import * as trpc from '@trpc/server' +import { TRPCError } from '@trpc/server' +import { createRouter } from '../createRouter' + +export const router = trpc + .router() + // this is accessible for everyone + .query('hello', { + input: z.string().nullish(), + resolve: ({ input, ctx }) => { + return `hello ${input ?? ctx.user?.name ?? 'world'}` + }, + }) + .merge( + 'admin.', + createRouter() + // this protects all procedures defined next in this router + .middleware(async ({ ctx, next }) => { + if (!ctx.user?.isAdmin) + throw new TRPCError({ code: 'UNAUTHORIZED' }) + + return next() + }) + .query('secret', { + resolve: ({ ctx }) => { + return { + secret: 'sauce', + } + }, + }), + ) +``` + +Learn more about authorization [here](https://trpc.io/docs/authorization). diff --git a/recipes/validation.md b/recipes/validation.md index 7162360..99856fb 100644 --- a/recipes/validation.md +++ b/recipes/validation.md @@ -1,6 +1,6 @@ ## Validation -tRPC works out-of-the-box with yup/superstruct/zod/myzod/custom validators. Learn more about input validation [here](https://trpc.io/docs/router#input-validation). +tRPC works out-of-the-box with yup/superstruct/zod/myzod/custom validators. ## Input Validation @@ -45,3 +45,5 @@ export const router = trpc }, }) ``` + +Learn more about input validation [here](https://trpc.io/docs/router#input-validation).