Does anyone have a good understanding of the Prism...
# orm-help
j
Does anyone have a good understanding of the Prisma middleware? What is the return value of the middlware callback used for? How are errors handled? The documentation is silent on these questions. They only really have simple examples.
r
Hi @Jason Kleinberg - I've not used it but looking at the docs and this single piece of middleware and query:
Copy code
prisma.$use(async (params, next) => {
  console.log(params.args.data.title)
  console.log('1')
  const result = await next(params)
  console.log('6')
  return result
})

//along with:
const create = await prisma.post.create({
  data: {
    title: 'Welcome to Prisma Day 2020',
  },
})
It seems like the
prisma.post.create
is "triggered" which would start the middleware. The middleware (as above) would run the first 2 lines (
console.logs
) and then do
const result = await next(params)
I think that does the actual
prisma.post.create
and returns the result to
result
in the middleware.Still in the middleware,
console.log('6')
would be run and then the result from the actual query returned
Basically the
await next(params)
would either call the next piece of middleware (if there is one) or would do the actual query and return the result..
So in https://www.prisma.io/docs/concepts/components/prisma-client/middleware#running-order-and-the-middleware-stack the
const result = await next(params)
in
// Middleware 3
is what runs the actual
prisma.post.create(
query and it returns the result of that back to
Middleware 2
which eventually returns it back to
Middleware 1
which in turn passes it back to the
const create
in :
Copy code
const create = await prisma.post.create({
  data: {
    title: 'Welcome to Prisma Day 2020',
  },
})
I guess errors could be handled with a standard
try .. catch
that you could put anywhere .. If the actual query (in
Middleware 3
) throws an error then it should bubble up until it gets to the "nearest`
try .. catch
block ..
I hope this makes some sense.. 😄
j
Thank you very much for your response. I was thinking that the middleware passes
params
in a chain, rather than composed. It’s obvious in retrospect.