Is there a way to implement a transaction-per-request middleware when using Hot Chocolate?

Viewed 782

Our team has implemented transaction middleware in our aspnet core app. At the beginning of the request, we begin a transaction and then delegate to the next middleware. If any unhandled exceptions occur, we rollback the transaction - otherwise we commit. Unfortunately, this doesn't seem to work within Hot Chocolate. It seems to handle the exceptions internally. Is there something we can examine (in an aspnet core context) to determine if there were any unhandled exceptions?

1 Answers

With V11 you have a few issues with this approach. The resolvers in v11 are executed in parallel. Therefor you will run into concurrency issues if you want to share a db context or a scope of it.

You can read more about ef and HotChocolate here: https://chillicream.com/docs/hotchocolate/integrations/entity-framework/

In GraphQL you really only need a transaction scope in the mutations. Mutations are only allowed as top level fields

mutation {
   updateUserName(input: {id:1233, name:"foo"}) {
      errors {
         message
      }
      user {
          username
      }
   }
}

Something like this is invalid

mutation {
   updateUser(id:1233) {
      name(value: "foo") {
         value 
      }
   }
}

As only top level fields can have side effects, you can just create your transaction scope there. You can even define a middleware for it if you do not want to repeat yourself:

https://github.com/ChilliCream/graphql-workshop/blob/master/docs/5-understanding-middleware.md

Related