Add fallback_value option to Field #4069
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #4020. This adds a parameter called
:fallback_value
to Field, which allows you to specify a value to be returned if the usual ways (calling the method on an object, or checking for the key in a hash) fail. It's useful if there is a query that returns objects that might or might not have a certain field.The motivation for this is a scenario where we have a data model that has lots of entity types. All of them have an
id
property. Most of them have aname
property, but some of them don't. We want all of them to implement an interface (Node) that has a requiredid
property and an optionalname
property.The default for the
:fallback_value
param in the initializer is:not_given
, which allows us to setnil
as the fallback if we want. The most common use case is probably with interfaces, so that's where I wrote tests. Are there any other places this should be tested? I added documentation to guides/fields/introduction.md underField Resolution
. Does that seem sufficient? I added a blurb to the error message about supplying afallback_value
to implement the field.