Anyone found a nice way to add resolver middleware...
# prisma-whats-new
p
Anyone found a nice way to add resolver middleware in Prisma? 🙂 e.g. add a user to the Context for specific resolvers
m
You could just define a helper function which takes
context
as an argument, and use it in your resolvers.
p
Yeah I agree, but the beauty of express middleware is that you can bind a user to the context for all routes (e.g. all routes behind
/admin/
get the admin user in the context). This prevents the situation where we have to call a helper function in every resolver.
I'll go with the helper functions for now 🙂 But i'll keep en eye out for a more DRY solution 😛
s
@agartha sounds like a good application for your middleware lib
👍🏻 2
h
graphql-tools custom @directives (schema sugar for GraphQL SDL) are the way to go to augment a resolver or field. Basically run some code before or after a resolver, for example '@toUpper' could set the text of a field to upper case before returning to client, or @withLoginToThirdPartyAPI could ensure you are authed with any third party API before running the resolver that calls it. Not very well documented at this moment in time but I managed to piece together both of the above concepts into my API thats using Prisma for the data layer. A small example can be seen here: https://github.com/apollographql/graphql-tools/issues/530 From the example there you will have an exported 'schema', just pass this in the the GraphQLServer instance along with prisma const server = new GraphQLServer({ schema: schema, context: req => ({ ...req, db: new Prisma({ typeDefs: 'src/generated/prisma.graphql', endpoint: process.env.PRISMA_ENDPOINT, // the endpoint of the Prisma DB service (value is set in .env) secret: process.env.PRISMA_SECRET, // taken from database/prisma.yml (value is set in .env) debug: true, // log all GraphQL queries & mutations }), }), }) You can swap the order of 'next()' in the directiveResolver to perform your action before or after the resovler. When doing before, like my loginToThirdPartyAPI example, I Object.Assign'ed my authed object to the context to make it available to my resolver.
fast parrot 1
p
That seems to be exactly what I'm looking for! Thnx 😄 !