"Router" folder

🎥 Watch the "router" folders section of the "Server Global State (TanStack/React Query)" style guide video here.

(OLD) Video overview ("router" folder & "route" folder): link


Our "api" object stores all of the individual "router" objects (e.g. fileCategories router, etc.), and can be imported in any component in order to access/modify any external data. Read more about the "api" object here.


For any external data, including our own backend, a "router" folder should be made.


The contents of the "router" folder are:

index.ts

Exports the "router" object (via router.ts), as well as anything else that needs to be used outside of the "router" folder (e.g. schemas and types)

router.ts

Contains the "router" object, which has methods (procedures) for accessing/modifying the data (e.g. getSingle, getMany, create, update, delete, etc.).

Any reusable procedure-supplying hooks (e.g. useBasicCRUDRoute, useBasicRelationshipRoute, etc.) are imported, and any custom procedures can be created here.

schema.ts

Contains source of truth for the external data's schema. We have two schema s for all external data:

  • "Backend" schema (TDocBE)

    • the original schema of the data, as it comes from its source

  • "Frontend" schema (TDoc)

    • the original schema converted to have all the field names be camelCase, at a minimum (see more about this in the adapter.ts section below)

types.ts

Contains source of truth for the external data's types.

Ultimately, our types are automatically inferred from our schemas in schema.ts, so our schemas are our ultimate single source of truth for types as well. (This is made possible by the Zod schema validation library ❤️)

adapterFns.ts

Contains the adapter functions for mapping one schema to another.

Ultimately, when receive external data (our backend, external API, etc.), it should go through two steps:

  • (1) schema validation

    • This confirms the data we are receiving is of the schema we expect

  • (2) an adapter function.

    • This maps/converts the data from its original schema (original field names, original data types, etc. -- aka our schemaBE in schema.ts) to our frontend schema (our decided upon schema for how we want to use it throughout our frontend -- aka our schema in schema.ts)

    • This mapping allows us to have a consistent and reliable (frontend) schema to use throughout our app, without requiring any change if the external data's original schema changes over time. (If it does change over time, we only have to update the schemaBE and adapter functions, rather than needing to make many changes wherever this data is used throughout our app)

We have two adapter functions:

  • Backend-to-Frontend (BE > FE)

    • (read more in code sample below)

  • Frontend-to-Backend (FE > BE)

    • (read more in code sample below)

Last updated