graphql-js
graphql-js copied to clipboard
Passing arguments into the resolvers by just using `buildSchema` and `graphql`?
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?
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
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 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});
});