jack
jack2y ago

best practices for organizing routes/procedures?

i'm trying to find some practices/styles in which people generally define routes with trpc. currently im just doing a router per data entity, and defining crud operations on there, but there's a lot of caveats that are kind of defined with REST, that i'm unsure of how to handle here. one idea i had was to define my router as such: (assume each subrouter will have routes)
export const selectionRouter = createTRPCRouter({
// CREATE
create: createTRPCRouter({}),
// READ
read: createTRPCRouter({
getAllValidSelections: publicProcedure.query(async ({ ctx }) => {...}),
}),
// UDPATE
update: createTRPCRouter({
editSelections: protectedProcedure.mutation(async ({ ctx, input }) => {...}),
}),
// DELETE
delete: createTRPCRouter({}),
});
export const selectionRouter = createTRPCRouter({
// CREATE
create: createTRPCRouter({}),
// READ
read: createTRPCRouter({
getAllValidSelections: publicProcedure.query(async ({ ctx }) => {...}),
}),
// UDPATE
update: createTRPCRouter({
editSelections: protectedProcedure.mutation(async ({ ctx, input }) => {...}),
}),
// DELETE
delete: createTRPCRouter({}),
});
another thing is reusing logic- i have a getSelectionsById, and a getOwnSelections. of course, these are gonna have a lot overlap because its entirely the same logic, but in one i'm passing conditional ids, and in the other im passing the session id. of course i could extract this out, but it feels inconsistent with the rest of the logic living inside of the router. i'm sure there's no clear cut answer for most of this, but i was just wondering how people generally go about this, or if there are any guides or blogs about this topic.
1 Reply
Nick
Nick2y ago
Most of what you've learned in REST-land does transfer over. Routers for entities is a just a sane way to structure your code, but it's a little more natural to have a procedural function Context and Middlewares can inject services/invert-control, so the DI techniques you may have learned with Controllers can also be adapted If you have a lot of similar CRUD routers you can also use factories to create those routes with a little configuration - I do this a lot

Did you find this page helpful?