From c48556e24eaafbdbec93c7d4e30a824519142e58 Mon Sep 17 00:00:00 2001 From: Robert Soriano Date: Thu, 19 May 2022 10:50:50 -0700 Subject: [PATCH] add merging routers recipe --- README.md | 1 + recipes/merging-routers.md | 47 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 recipes/merging-routers.md diff --git a/README.md b/README.md index 3d3a4af..a267117 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,7 @@ export const onError = (payload: OnErrorPayload) => { - [Validation](/recipes/validation.md) - [Authorization](/recipes/authorization.md) +- [Merging Routers](/recipes/merging-routers.md) - [Error Handling](/recipes/error-handling.md) - [Error Formatting](/recipes/error-formatting.md) diff --git a/recipes/merging-routers.md b/recipes/merging-routers.md new file mode 100644 index 0000000..5cb179e --- /dev/null +++ b/recipes/merging-routers.md @@ -0,0 +1,47 @@ +# Merging Routers + +Writing all API-code in your code in the same file is not a great idea. It's easy to merge routers with other routers. + +```ts +// ~/server/trpc/routes/posts.ts +export const posts = trpc.router() + .mutation('create', { + input: z.object({ + title: z.string(), + }), + resolve: ({ input }) => { + // .. + return { + id: 'xxxx', + ...input, + } + }, + }) + .query('list', { + resolve() { + // .. + return [] + } + }) +``` + +```ts +// ~/server/trpc/routes/users.ts +export const users = trpc.router() + .query('list', { + resolve() { + // .. + return [] + } + }) +``` + +```ts +// ~/server/trpc/index.ts +import { users } from './routes/users' +import { posts } from './routes/posts' + +export const router = trpc.router() + .merge('user.', users) // prefix user procedures with "user." + .merge('post.', posts) // prefix post procedures with "post." +```