Hello,
is it possible to assign default values to fields?
For example:
field :my_field, String, null: false, default_value: "My default value"
The guides talk about default value in arguments https://graphql-ruby.org/fields/arguments.html but I didn't find anything about default values for fields.
Thanks!
No, that configuration isn't supported. (Argument default values are defined in the GraphQL spec, eg http://spec.graphql.org/June2018/#sec-Coercing-Field-Arguments.)
Of course, you can implement something like that with
field :my_field, String, null: false
def my_field
object.my_field || "Default value"
end
I hope that helps!
Thanks a lot! This will help! I'm writing a proof of concept for a framework to quickly build schemas in a standardized way. Not sure if my ideas will work out in the end, but either way it's a lot of fun and I learn much about graphql-ruby. If you're interested, I can keep you in the loop if I have something substantial. :rocket:
Cool, at a framework level, you could probably implement it with a Field Extension (https://graphql-ruby.org/type_definitions/field_extensions.html), eg
class DefaultValueExtension < GraphQL::Schema::FieldExtension
def after_resolve(value:, **_rest)
if value.nil?
options[:default_value]
else
value
end
end
end
Like
class Types::BaseField < GraphQL::Schema::Field
def initialize(*args, default_value: nil, **kwargs, &block)
super(*args, **kwargs, &block)
if !default_value.nil?
extension(DefaultValueExtension, default_value: default_value)
end
end
end
Then:
field :some_string, String, null: false, default_value: "馃帀"
Hope that helps!
Hey thanks a lot. I will look into that. Looks exactly like what I had in mind. I guess I will publish a first draft in the following weeks. Looking forward to hear what you think about it. Have a nice weekend!
Most helpful comment
Cool, at a framework level, you could probably implement it with a Field Extension (https://graphql-ruby.org/type_definitions/field_extensions.html), eg
Like
Then:
Hope that helps!