Express-graphql: Hooking into the Express response object in the resolver

Created on 9 Nov 2016  路  2Comments  路  Source: graphql/express-graphql

How do I get access to the express response object within the rootValue resolver method?

i.e.

app.use('/api/messages', graphqlHTTP({
  schema: SpatialMessageSchema,
  rootValue: SpatialMessageResolver,
  graphiql: true,
}));

myResolver(args, res){

Most helpful comment

Hey Erik,

You can check out the example in https://github.com/graphql/express-graphql#providing-extensions which illustrates using the original response object

For your case of wanting to use request as the rootObject, you could do:

app.use('/api/messages', graphqlHTTP(request => ({
  schema: SpatialMessageSchema,
  rootValue: request,
  graphiql: true,
})));

If you need to do some work before resolving the GraphQL request, then yes you can return a Promise.

app.use('/graphql', graphqlHTTP(request => {
  return doSomethingSlowThenPromise().then(() => ({
    schema: mySchema,
    graphiql: true
  }))
})

You can also always use middleware ahead of the GraphQL middleware:

// some random middleware that takes a minute
app.use('/graphql', (req, res, next) => {
  doSomethingSlowThenCall(value => {
    req.someValue = value;
    // then continue
    next();
  })
});

app.use('/graphql', graphqlHTTP(request => ({
  schema: mySchema,
  rootValue: request.someValue,
  graphiql: true
}))

All 2 comments

@leebyron Is the suggested approach with handling express resolvers to return a Promise?

Hey Erik,

You can check out the example in https://github.com/graphql/express-graphql#providing-extensions which illustrates using the original response object

For your case of wanting to use request as the rootObject, you could do:

app.use('/api/messages', graphqlHTTP(request => ({
  schema: SpatialMessageSchema,
  rootValue: request,
  graphiql: true,
})));

If you need to do some work before resolving the GraphQL request, then yes you can return a Promise.

app.use('/graphql', graphqlHTTP(request => {
  return doSomethingSlowThenPromise().then(() => ({
    schema: mySchema,
    graphiql: true
  }))
})

You can also always use middleware ahead of the GraphQL middleware:

// some random middleware that takes a minute
app.use('/graphql', (req, res, next) => {
  doSomethingSlowThenCall(value => {
    req.someValue = value;
    // then continue
    next();
  })
});

app.use('/graphql', graphqlHTTP(request => ({
  schema: mySchema,
  rootValue: request.someValue,
  graphiql: true
}))
Was this page helpful?
0 / 5 - 0 ratings

Related issues

KieronWiltshire picture KieronWiltshire  路  3Comments

justinmchase picture justinmchase  路  4Comments

arunoda picture arunoda  路  4Comments

m-diiorio picture m-diiorio  路  4Comments

stevvvn picture stevvvn  路  3Comments