sh03
sh032y ago

How to organise reusable functions

How do you guys organize functions that all need the same context (usually from tRPC)? For example let's say that you have 10 functions you use multiple times across multiple routers and they all share the same context. Do you use a class?
16 Replies
Nick
Nick2y ago
Can you share an example?
sh03
sh032y ago
E.g. a function that given an input user ID checks a bunch of properties on that user (e.g. for an educational app that the current user has a valid teacher's contract) Or a function that checks that some invariants are hold during certain operations (e.g. for a calendar app that multiple events don't overlap on the same calendar when: moving, swapping, rescheduling, etc.)
Nick
Nick2y ago
Probably makes sense to type the function just with the deps it needs, rather than a full Context These just sound like utilities so ideally should be too coupled to the APi right?
sh03
sh032y ago
It's kinda cumbersome to do that though. It's also difficult to enforce that the parameter is the first/last of the series of arguments so you end up with an inconsistent library TBH I don't see the context as part of the API The context is more of a business logic piece in my mind
Nick
Nick2y ago
This is definitely a case of "move stuff around until it feels right" tRPC doesn't really have any strong opinions about how to do this
sh03
sh032y ago
Yeah I know, I was just wondering how you guys get by
Nick
Nick2y ago
Personally, I put service classes into the Context and use it like DI, then have some utility functions without any strong pattern for their interfaces
sh03
sh032y ago
Wdym by "putting service classes into the context" exactly? Sounds like what I'm looking for
Nick
Nick2y ago
using createContext I instantiate any services I need and then procedures can consume them Like ORM Repositories, API Clients, etc
sh03
sh032y ago
So then you call something like ctx.someService.create(...)?
Nick
Nick2y ago
You can also use middlewares to extend the Context with extra services if you want to scope them If you like No right answers here, just what fits your needs/opinions
sh03
sh032y ago
I know, but I'm trying to understand what your way is and if it works for you
Nick
Nick2y ago
my way supports this usage ctx.db.findById(id) already created
sh03
sh032y ago
I'm assuming db there is your repository or a Prisma extended client. What about your services?
Nick
Nick2y ago
Everything done the same way, just a namespace on ctx
sh03
sh032y ago
I think I got it thanks