How do I set up a (database or other) context in the GraphQL transformer?

The GraphQL docs provide an example of a resolver function that takes an argument called a context.

They have to say this about it -

context

A value that is provided to each resolver and contains important contextual information such as the current login user or database access.

And their example code looks like this:

Query: {
  human(obj, args, context) {
    return context.db.loadHumanByID(args.id).then(
      userData => new Human(userData)
    )
  }
}

      

It seems like a perfectly natural way to access the database inside the resolver function, and unsurprisingly, this is what I need to do.

This database context is not automatically configured, obviously since GraphQL is completely agnostic about your particular persistence means.

My question is, how do I set up this context to provide one specific db interface? I cannot find any mention of this in the tutorials / docs or anywhere else.

+3


source to share


2 answers


You can pass context to graphql when calling the function graphql

.
It is listed here .

Here is the definition of a function flow graphql

:



graphql(
  schema: GraphQLSchema,
  requestString: string,
  rootValue?: ?any,
  contextValue?: ?any, // Arbitrary context
  variableValues?: ?{[key: string]: any},
  operationName?: ?string
): Promise<GraphQLResult>

      

+2


source


Context

defined when configuring the server. I also couldn't see this in the docs.



graphqlExpress(req => {
  return {
    schema: makeExecutableSchema({
      typeDefs: schema.ast,
      resolvers,
      logger
    }),
    context: {
      db: mongodb.MongoClient.connect(...)
    }
  };
})

      

+3


source







All Articles