add merging routers recipe

This commit is contained in:
Robert Soriano
2022-05-19 10:50:50 -07:00
parent f3e0165dd8
commit c48556e24e
2 changed files with 48 additions and 0 deletions

View File

@@ -131,6 +131,7 @@ export const onError = (payload: OnErrorPayload<typeof router>) => {
- [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)

View File

@@ -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."
```