问题
When we are using graphqlHTTP, the first argument passed to the resolve method is actually the parameters passed by the client query not root this is fine for a query resolver. But for a usecase where field resolver needs to know of a value of the parent, how to achieve this?
type Person {
name: String,
cityId: String,
city: City,
}
In the above scenario I would like where city would be a field resolver, and it needs access to cityId which is a property on parent type. I assume this should have been passed as parameter to the field resolver but that is not the case. Is there a way to achieve this?
I see same can be done when schema is declared using objects, in that case the firs value passed to resolver functions is root.
回答1:
Short answer: don't use buildSchema.
Passing resolve functions through the root value only works because it relies on the default resolver behavior, and it only works for root-level fields. Unfortunately, if you use buildSchema
, the only way to provide resolvers is through the root value.
Your options are:
Build your schema programatically instead of using Schema Definition Language (SDL). This will allow you to specify a
resolve
function for any field in your schema, and that resolve function will get all four parameters (parent value, arguments, context and info). You can check out the docs for some examples.Write your schema in SDL but use
makeExecutableSchema
fromgraphql-tools
to generate your GraphQLSchema instance.makeExecutableSchema
allows you to painlessly inject resolvers for any fields and provides a number of other features. More information about how to generate a schema this way can be found here.Dump
express-graphql
forapollo-server
, which usesmakeExecutableSchema
under the hood and provides a number of additional features thatexpress-graphql
does not. Check the docs for how to get started.
来源:https://stackoverflow.com/questions/54792757/how-to-access-the-value-of-parent-resolver-inside-a-field-resolver-while-using-b