How is <this example of session data middleware> f...
# orm-help
d
How is this example of session data middleware from the documentation accessing the session context? The example code just puts it in some magic global variable, but that's not realistic. I'd let to get the tenant id from my graphql context and us it in middleware to scope queries to the tenant. My use case seems very analogous to the example, but a real-world version of the example seems impossible based on what I've read about the middleware API so far. Any tips of achieving this?
1
a
There are multiple ways of doing this and it's up to the developers team to figure out a way of doing such thing. I think
middleware
is not necessary in here as adding such data can be done without middleware. However, if middleware is required, here's a quick simple example: When you get the request, set a global instance that records the session data and the ID of the record about to be created (pass ID manually). The middleware can then use that instance and compare the ID to get the session data then remove that entry from the global instance. Another example is to reset prisma on each request and define the middleware during the request (which will have access to the session data), not a great solution, but it keeps it clean. Too bad Prisma won't allow deleting middleware, another good way to do this imo is to define the middleware at the beginning of the request, then removing it at the end of it. Maybe we should raise a ticket for this feature.
d
Thanks for weighing in Aladin. I think async_hooks could be the best solution here, as the mechanism you described for the middleware inferring which session context it is executing in does not seem like it would work well in our application. Perhaps I don't understand what you mean by "ID of the record about to be created".
But I am curious to know if Prisma has any direct advice here, and whether async_hooks would be problematic for reasons I'm not seeing.
a
By ID of the record I mean this: • Make a SessionMiddlewareData object outside of the request context • Request comes in • Request is supposed to create a Post, so it generates a
postId
• Add
sessionMiddlewareData.add(postId, { ...stuff here })
• In the middleware, when creating a Post or updating it, you can call
sessionMiddlewareData.get(params.args.data.id)
to get the data you recorded earlier and clean it up
d
Thanks for explaining further. That approach will not generalize to complex queries as far as I can tell. In general, it is not possible to infer the ID of every single database record that will need to be modified during the course of the request from the parameters of the request itself.