Middleware or request lifecycle hook to run after procedure?
Hi,
I am using trpc context to create a database client for an incoming request. My understanding is this runs for every request, which is what I want.
I want to be able to systematically close the databaase client at the end of any TRPC request. Is there any way of doing this? Perhaps with a middleware or request lifecycle hook? I couldn't find any documentation on it.
This is the structure I want:
Thank you!
Solution:Jump to solution
is this sort of what you mean?
```
const withDb = middleware((opts) => {
const db = getServerlessDBInstance();...
11 Replies
Yep just await
next()
into a variable, do your work, and then return the variable
But generally with DBs you want to have a persistent pool, opening and closing connections is expensive, so maintaining a pool instance means there are always some open connections availableI am using Neon (neon.tech) as my DB provider and they explicitly say to close it at the end of every request:
from here: https://neon.tech/docs/serverless/serverless-driver
Neon
Neon serverless driver - Neon Docs
The Neon serverless driver is a low-latency Postgres driver for JavaScript and TypeScript that allows you to query data from serverless and edge environments over HTTP or WebSockets in place of TCP. Y...
Can you explain what you mean why the awaiting the
next()
variable? I would like the procedure to have access to the ctx.db, but not have to remember to close it
Oh I think I see what you mean.
Like the middleware would be:
is that what you mean?Fair enough then! Obviously their advice takes precedence 🙂
Yep! Middlewares are flexible 🙂
got it, thank you! I will try that out
You can add the DB in to the ctx by passing it to next() as well
ahh perfect ok
it will be merged, no pain needed from you
Solution
is this sort of what you mean?
(obviously I will add the db.end() as well)
Exactly