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.

Thanks to TypeScript 4.1 template literal types we can also prefix the procedures without breaking typesafety.

Working example

Example code

server.ts

  1. const createRouter = () => {
  2. return trpc.router<Context>();
  3. }
  4. const posts = createRouter()
  5. .mutation('create', {
  6. input: z.object({
  7. title: z.string(),
  8. }),
  9. resolve: ({ input }) => {
  10. // ..
  11. return {
  12. id: 'xxxx',
  13. ...input,
  14. }
  15. },
  16. })
  17. .query('list', {
  18. resolve() {
  19. // ..
  20. return []
  21. }
  22. });
  23. const users = createRouter()
  24. .query('list', {
  25. resolve() {
  26. // ..
  27. return []
  28. }
  29. });
  30. const appRouter = createRouter()
  31. .merge('user.', users) // prefix user procedures with "user."
  32. .merge('post.', posts) // prefix post procedures with "post."
  33. ;