Skip to content

Passing arguments into the resolvers by just using buildSchema and graphql? #3976

@lautiamkok

Description

@lautiamkok

How can we pass arguments into the resolvers by just using buildSchema and graphql?

My code:

var schema = buildSchema(`
 type Query {
    hello: String
    greet(name: String): String
  }
`)

var rootValue = {
  hello: (root, args, context, info) => {
    return "Hello world!"
  },

  greet: (root, args, context, info) => {
    console.log('args =', args)
    return 'Hello ' + args.name
  },
}

const requestListener: http.RequestListener = async (req, res) => {
  if (req.url === '/' || req.url.startsWith('/graphql')) {
    res.setHeader('Content-Type', 'application/json')
    res.statusCode = 200
    
    const source =  `query { greet(name: "John") }`
    const response = await graphql({
      schema,
      source,
      rootValue,
    })
    res.end(JSON.stringify(response))
  } 
}

Result:

{"errors":[{"message":"Cannot read properties of undefined (reading 'name')","locations":[{"line":1,"column":9}],"path":["greet"]}],"data":{"greet":null}}

Result for console.log('args =', args):

args = undefined

Any ideas?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions