mintyM
tRPC3y ago
17 replies
minty

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:
1. Request start
2. Context is created --> DB open
3. Procedure runs
4. DB is closed


Thank you!
Solution
is this sort of what you mean?

const withDb = middleware((opts) => {
  const db = getServerlessDBInstance();

  const result = opts.next({ ctx: { db } });

  return result;
});
Was this page helpful?