Hello,
I have a small and possible simple question about access to nested field arguments
Types:
type NestedField {
value: String!
}
type Example {
nestedField(arg: Int!): NestedField
}
type Query {
getExample: Example!
}
Query:
{
getExample {
nestedField(arg: 1) {
value
}
}
}
Resolvers:
const resolvers = {
Query: {
getExample(_, args) {
console.log('============================================');
console.log(JSON.stringify(args, null, 2));
return {
nestedField: {
value: 'test'
}
};
}
}
};
In args I have an empty object, but I checked query itself contains data about an argument. How can I get access to it in my resolver? Thanks!
Even though you seem to have found the answer yourself, it would be great if you could provide your solution to other people who might find this issue.
Yep, sure, solution, as I expected is easy. Instead of returning value for the nested field, we need to return a function that will return a value. And in this function will be an argument for the nested field:
const resolvers = {
Query: {
getExample(_, args) {
console.log('============================================');
console.log(JSON.stringify(args, null, 2));
return {
nestedField({ arg }) {
return {value: `test${arg}`}
}
};
}
}
};
This example doesn't seem to work, with the following...
````javascript
import { GraphQLServer } from 'graphql-yoga'
const typeDefs =
type NestedField {
value: String!
}
type Example {
nestedField(arg: Int!): NestedField
}
type Query {
getExample: Example!
}
const resolvers = {
Query: {
getExample(_, args) {
console.log('============================================');
console.log(JSON.stringify(args, null, 2));
return {
nestedField({ arg }) {
return {value: test${arg}}
}
};
}
}
};
const server = new GraphQLServer({ typeDefs, resolvers })
server.start(() => console.log('Server is running on localhost:4000'))
````
I get Error: Cannot return null for non-nullable field NestedField.value.. I can't seem to get sub-resolvers to work at all with GraphQL Yoga.
Most helpful comment
Yep, sure, solution, as I expected is easy. Instead of returning value for the nested field, we need to return a function that will return a value. And in this function will be an argument for the nested field: