Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add GraphQL::Types::ISO8601DateTime.time_precision to customize time pricisions #1845

Merged
merged 1 commit into from
Sep 10, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion lib/graphql/types/iso_8601_date_time.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
25 changes: 25 additions & 0 deletions spec/graphql/types/iso_8601_date_time_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down