Router
A router is responsible for collecting up procedures. Once a router is built you are provided with the types for generating the client bindings and the procedure handlers which can be exposed via an integration.
TCtx
The type of the request context. This is usually a struct
containing state coming from the webserver such as a database connection and user session.
For example:
Constructing an rspc router with a specific context type is done as following.
TCtx
is super powerful in rspc because middleware are able to change it for procedures following them in the chain. A great example of this in action is an authentication middleware like shown below.
Attaching procedures
Procedures represent a function you define in Rust which can be called from the frontend. You can define them on your routing like the following example.
Should I use a query or a mutation?
Does your operation have side effects? If so, use a mutation else, use a query.
A query should not change any data on the server, it should just be responsible for fetching data. A mutation should be responsible for changing data on the server.
Merging routers
When building an API server, you will often want to split up your endpoints into multiple files to make the code easier to work on. You can combine routers using the .merge
method.
router.merge(prefix: &'static str, router: Router)
Exporting the Typescript bindings
There are two methods to export the Typescript bindings. You can either use the export_ts_bindings
configuration option or call the export_ts
function directly on the build router.
You can also use the set_ts_bindings_header
option on the Config
if you want to add a custom header to the top of the generated file. This is useful to disable ESLint, Prettier or other similar tools from processing the generated file.
TODO
- Request context (show putting data into it)
- Show how to achieve websocket-scoped context via middleware (we
Clone
the context) - Type exporting
- Explain
merge
andnest
- "Should I use a query or a mutation?" as tip or even Accordion?
Last updated on