Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
lautiamkok opened this issue Oct 10, 2023 · 4 comments
Closed

Comments

@lautiamkok
Copy link

lautiamkok commented Oct 10, 2023

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?

@xonx4l
Copy link

xonx4l commented Oct 14, 2023

The error message "Cannot read properties of undefined (reading 'name')" indicates that the name argument is undefined within your resolver.In this updated version, we are using destructuring to extract the name argument directly from the arguments object.Additionally, when constructing the GraphQL query in the source variable, we'll ensure that we're properly passing the name as a query parameter

@xonx4l
Copy link

xonx4l commented Oct 14, 2023

const requestListener = async (req, res) => {
if (req.method === 'GET' && (req.url === '/' || req.url.startsWith('/graphql'))) {
res.setHeader('Content-Type', 'application/json');
res.statusCode = 200;

const urlParams = new URLSearchParams(req.url.split('?')[1]);
const name = urlParams.get('name');

const source = `query { greet(name: "${name || 'John'}") }`;
const response = await graphql({
  schema,
  source,
  rootValue,
});
res.end(JSON.stringify(response));

} else {
res.statusCode = 404;
res.end('Not Found');
}
};

@xonx4l
Copy link

xonx4l commented Oct 14, 2023

const http = require('http');
const { graphql, buildSchema } = require('graphql');

const schema = buildSchema(type Query { hello: String greet(name: String): String });

const rootValue = {
hello: () => {
return 'Hello, world!';
},
greet: ({ name }) => {
return Hello, ${name || 'Stranger'}!;
},
};

const requestListener = async (req, res) => {
if (req.method === 'GET' && (req.url === '/' || req.url.startsWith('/graphql'))) {
res.setHeader('Content-Type', 'application/json');
res.statusCode = 200;

const urlParams = new URLSearchParams(req.url.split('?')[1]);
const name = urlParams.get('name');

const source = `query { greet(name: "${name || 'John'}") }`;
const response = await graphql({
  schema,
  source,
  rootValue,
});
res.end(JSON.stringify(response));

} else {
res.statusCode = 404;
res.end('Not Found');
}
};

const server = http.createServer(requestListener);
const PORT = 3000;

server.listen(PORT, () => {
console.log(Server is listening on port ${PORT});
});

@JoviDeCroock
Copy link
Member

The above is partially correct, you can also leverage variables like

query ($name: String) {
  greet(name: $name)
}

At which point the request payload will look like query: "", variables: { name: "x" }. To add in variables to your graphql() invocation you can add variableValues: body.variables

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants