Graphql-Access arguments in child resolvers
If you know you are using variables there is another way, other than the accepted answer, using the fourth argument of the resolver function: info
.
This info
argument contains a field variableValues
amongst other fields.
This field doesn't strictly contain the parent's args
, but if your operation is executed with variables that are passed to the parent resolver, then you'll have access to them via the info.variableValues from all the relevant resolver functions.
So if your operation is called like this for example:
query GetTotalVehicalsOperation($color: String) {
getTotalVehicals(color: $color) {
totalCars
totalTrucks
}
}
... with variables: {color: 'something'}
you'll have access to the variables from the other resolvers:
{
RootQuery: {
getTotalVehicles: async (root, args, context, info) => {
//info.variableValues contains {color: 'something'}
return {};
},
TotalVehicleResponse: {
totalCars: async (root, args, context, info) => {
//same here: info.variableValues contains {color: 'something'}
},
totalTrucks: async (root, args, context, info) => {
//and also here: info.variableValues contains {color: 'something'}
}
}
}
}
args
refer strictly to the arguments provided in the query to that field. If you want values to be made available to child resolvers, you can simply return them from the parent resolver.
{
RootQuery: {
getTotalVehicles: async (root, args, context) => {
return { color: args.color };
},
TotalVehicleResponse: {
totalCars: async (root, args, context) => {
// root contains color here
},
totalTrucks: async (root, args, context) => {
// root contains color here
}
}
}
}