From b7af23dad3ceeeab3cf605e654134e51112e4a1d Mon Sep 17 00:00:00 2001 From: "FUJI Goro (gfx)" Date: Mon, 10 Sep 2018 11:11:36 +0900 Subject: [PATCH] add GraphQL::Types::ISO8601DateTime.time_precision to customize time precisions --- lib/graphql/types/iso_8601_date_time.rb | 16 +++++++++++- spec/graphql/types/iso_8601_date_time_spec.rb | 25 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/lib/graphql/types/iso_8601_date_time.rb b/lib/graphql/types/iso_8601_date_time.rb index 497adb9994..0382ccbb97 100644 --- a/lib/graphql/types/iso_8601_date_time.rb +++ b/lib/graphql/types/iso_8601_date_time.rb @@ -15,10 +15,24 @@ module Types class ISO8601DateTime < GraphQL::Schema::Scalar description "An ISO 8601-encoded datetime" + # It's not compatible with Rails' default, + # i.e. ActiveSupport::JSON::Encoder.time_precision (3 by default) + DEFAULT_TIME_PRECISION = 0 + + # @return [Integer] + def self.time_precision + @time_precision || DEFAULT_TIME_PRECISION + end + + # @param [Integer] value + def self.time_precision=(value) + @time_precision = value + end + # @param value [DateTime] # @return [String] def self.coerce_result(value, _ctx) - value.iso8601 + value.iso8601(time_precision) end # @param str_value [String] diff --git a/spec/graphql/types/iso_8601_date_time_spec.rb b/spec/graphql/types/iso_8601_date_time_spec.rb index e154b7d603..40d8157fec 100644 --- a/spec/graphql/types/iso_8601_date_time_spec.rb +++ b/spec/graphql/types/iso_8601_date_time_spec.rb @@ -90,6 +90,31 @@ def parse_date(date_str) full_res = DateTimeTest::Schema.execute(query_str, variables: { date: date_str }) assert_equal date_str, full_res["data"]["parseDate"]["iso8601"] end + + describe "with time_precision = 3 (i.e. 'with milliseconds')" do + before do + @tp = GraphQL::Types::ISO8601DateTime.time_precision + GraphQL::Types::ISO8601DateTime.time_precision = 3 + end + + after do + GraphQL::Types::ISO8601DateTime.time_precision = @tp + end + + it "returns a string" do + query_str = <<-GRAPHQL + query($date: ISO8601DateTime!){ + parseDate(date: $date) { + iso8601 + } + } + GRAPHQL + + date_str = "2010-02-02T22:30:30.123-06:00" + full_res = DateTimeTest::Schema.execute(query_str, variables: { date: date_str }) + assert_equal date_str, full_res["data"]["parseDate"]["iso8601"] + end + end end describe "structure" do