Express-graphql: Cannot access `context` object in resolve function

Created on 24 Aug 2018  路  3Comments  路  Source: graphql/express-graphql

Hi! Sorry for asking this question, but I'm new to express-graphql. Here's the simple example that I use to access the context in the resolver, but both of the request and the test field return undefined when I log it out to the console. I'm using "express-graphql": "^0.6.12" and "graphql": "^0.13.2".

const schema = buildSchema(`
  type Query {
    sum(num1: Int!, num2: Int!): Number!
  }

  type Number {
    num: Int!
  }
`)

const root = {
  sum: sumOfTwo
}

const sumOfTwo = (parent, args, context) => {
  console.log(context.test)
  const { num1, num2 } = args
  return {
    num: num1 + num2
  }
}

app.use('/graphql', graphqlHTTP((request, response, graphQLParams) => ({
  schema: schema,
  rootValue: root,
  graphiql: true,
  context: {
    request: request,
    test: 'Hello World'
  }
})))

Most helpful comment

@phuchle2 Thanks for the detailed description and minimal code sample 馃憤
TL;DR; just remove the parent from sumOfTwo arguments

When you use such parent values:

const root = {
  sum: sumOfTwo
}

root became parent for sumOfTwo so it's passed as this instead of first parameter.

All 3 comments

@phuchle2 Thanks for the detailed description and minimal code sample 馃憤
TL;DR; just remove the parent from sumOfTwo arguments

When you use such parent values:

const root = {
  sum: sumOfTwo
}

root became parent for sumOfTwo so it's passed as this instead of first parameter.

@phuchle2 BTW, If you can use ES6 classes they will make the code even more readable:
https://github.com/IvanGoncharov/swapi-demo/blob/master/src/index.ts

Thanks @IvanGoncharov! I will definitely work on ES6 classes :+1:

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dhurlburtusa picture dhurlburtusa  路  4Comments

macin40 picture macin40  路  4Comments

jamesmoriarty picture jamesmoriarty  路  4Comments

langpavel picture langpavel  路  5Comments

naivefun picture naivefun  路  3Comments