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

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