graphql-ruby, Date or Datetime type
Asked Answered
P

4

18

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?

Porterporterage answered 24/12, 2017 at 11:28 Comment(0)
P
33

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
Photoconductivity answered 22/7, 2018 at 16:14 Comment(0)
P
2

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
Presidency answered 1/2, 2018 at 13:27 Comment(0)
P
1

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

Putsch answered 8/2, 2018 at 1:58 Comment(0)
E
0

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
Elisavetpol answered 5/1, 2018 at 10:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.