Reputation:
I'm not the only one who doesn't know how to use Datetime
types with GraphQL-Ruby: https://github.com/rmosolgo/graphql-ruby-demo/issues/27, as you can see there are 18 people like me.
How can I use Datetime to some fields like this?
Types::PlayerType = GraphQL::ObjectType.define do
name 'Player'
field :id, !types.ID
field :birth_date, types.Datetime #or what?
field :death_date, !types.Datetime #or what?
field :note, types.String
end
Maybe I have to use this (https://github.com/howtographql/graphql-ruby/blob/master/app/graphql/types/date_time_type.rb):
date_time_type.rb:
Types::DateTimeType = GraphQL::ScalarType.define do
name 'DateTime'
coerce_input ->(value, _ctx) { Time.zone.parse(value) }
coerce_result ->(value, _ctx) { value.utc.iso8601 }
end
Can someone explain it better?
Upvotes: 18
Views: 10206
Reputation: 1518
GraphQL::Types::ISO8601DateTime
and GraphQL::Types::ISO8601Date
recently got added to graphql ruby library (Pull Request).
Usage example:
field :created_at, GraphQL::Types::ISO8601DateTime, null: false
field :starts_on, GraphQL::Types::ISO8601Date, null: false
Upvotes: 33
Reputation: 11
According to source code, there are only 5 types(Int, String, Float, Boolean, ID) defined as method which means you cannot use types.DateTime
.
To customize DateTimeType, you could reference its document of the gem and implement as the above you've mentioned about (date_time_type.rb), then you can use it like this:
field :birth_date, Types::DateTimeType
Upvotes: 1
Reputation: 99
The type declaration should properly work. Keep in mind that the DateTimeType you pasted is in the module "Types". Use it like this:
Types::PlayerType = GraphQL::ObjectType.define do
name 'Player'
field :id, !types.ID
field :birth_date, Types::DateTimeType
field :death_date, Types::DateTimeType
field :note, types.String
end
Upvotes: 2
Reputation: 16031
Not sure I have a better explanation, but I did get it to work by pasting the code from above to define my own scalar DateTimeType
:
DateTimeType = GraphQL::ScalarType.define do
name 'DateTime'
coerce_input ->(value, _ctx) { Time.zone.parse(value) }
coerce_result ->(value, _ctx) { value.utc.iso8601 }
end
MyType = ::GraphQL::ObjectType.define do
name 'MyType'
field :when, type: !DateTimeType
end
Upvotes: 0