Server
Router

Router

Another component of the PTSQ server instance is the router. This is used to create PTSQ endpoint paths and is inspired by a similar interface created by tRPC. However, the actual operation of the router is different and PTSQ routers offer introspection support. The routers define the API itself and offer a structured way to organize and manage endpoints.

Nesting allows you to create paths, similar to the REST architecture and its frameworks. Nesting routers provide a hierarchical structure that reflects the logical organization of the API.

Routers

Routers can be nested between files, instances of routers defined in one file can be exported and imported in another file and nested into an overarching router.

Server side
import { ptsq } from '@ptsq/server';
 
const { resolver, router } = ptsq().create();
 
const createUser = resolver
  .output(
    Type.Object({
      firstName: Type.String(),
      lastName: Type.String(),
    }),
  )
  .mutation(() => {
    return {
      firstName: 'John',
      lastName: 'Doe',
    };
  });
 
// routers can be nested as you want
const baseRouter = router({
  user: router({
    create: createUser,
  }),
});
 
export type BaseRouter = typeof baseRouter;

The keys inside the router object describe the path to the endpoint. The createUser mutation is assigned the path user.create. When another router is nested, the path can be modified or extended, such as organization.user.create. The endpoint itself does not affect the path assigned to it in any way. It is always the responsibility of one of the routers to create these paths, and it is recommended to create and group routers logically. For example, separate routers to manage users, posts, rooms, or other database models. Each router that represents a database model should, but need not, contain all CRUD operations for the complete ability to manage that model.

On client side

On the client side routers are objects (Proxy objects). If routers are nested on the server, it creates the nesting on the client side as well.

Client side
import { createProxyClient } from '@ptsq/client';
import type { BaseRouter } from './server';
 
const client = createProxyClient<BaseRouter>({
  url: 'http://localhost:4000/ptsq',
});
 
const response = await client.user.create.mutate();

Merging routers

In addition to nesting, routers also support merging using the static Router.merge method. This method creates a new router. The operation does not change the contents of the original routers in any way and merges the paths of one and the other. If any of the paths within the routers overlap, the path that enters the merge operation second, from the other router, is always used.

Server router merging
import { Router } from '@ptsq/server';
import { routerA } from './routerA';
import { routerB } from './routerB';
 
const mergedRouter = Router.merge(routerA, routerB);