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

Accept dates and datetimes in formatted string schemas #524

Merged
merged 2 commits into from
Feb 7, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 5 additions & 0 deletions lib/open_api_spex/cast/string.ex
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@ defmodule OpenApiSpex.Cast.String do
schema struct.

"""

alias OpenApiSpex.{Cast, Cast.Error}

@schema_fields [:maxLength, :minLength, :pattern]

def cast(%{value: %Date{} = date, schema: %{format: :date}}), do: {:ok, date}

def cast(%{value: value, schema: %{format: :date}} = ctx) when is_binary(value) do
case Date.from_iso8601(value) do
{:ok, %Date{} = date} ->
Expand All @@ -20,6 +23,8 @@ defmodule OpenApiSpex.Cast.String do
end
end

def cast(%{value: %DateTime{} = date_time, schema: %{format: :"date-time"}}), do: {:ok, date_time}

def cast(%{value: value, schema: %{format: :"date-time"}} = ctx) when is_binary(value) do
case DateTime.from_iso8601(value) do
{:ok, %DateTime{} = date_time, _offset} ->
Expand Down
10 changes: 8 additions & 2 deletions test/cast/string_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,11 @@ defmodule OpenApiSpex.CastStringTest do

test "string with format (date time)" do
schema = %Schema{type: :string, format: :"date-time"}
time_string = DateTime.utc_now() |> DateTime.to_string()
time = DateTime.utc_now()
time_string = to_string(time)

assert {:ok, %DateTime{}} = cast(value: time_string, schema: schema)
assert {:ok, ^time} = cast(value: time, schema: schema)
assert {:error, [error]} = cast(value: "hello", schema: schema)
assert error.reason == :invalid_format
assert error.value == "hello"
Expand All @@ -42,8 +45,11 @@ defmodule OpenApiSpex.CastStringTest do

test "string with format (date)" do
schema = %Schema{type: :string, format: :date}
date_string = DateTime.utc_now() |> DateTime.to_date() |> Date.to_string()
date = Date.utc_today()
date_string = to_string(date)

assert {:ok, %Date{}} = cast(value: date_string, schema: schema)
assert {:ok, ^date} = cast(value: date, schema: schema)
assert {:error, [error]} = cast(value: "hello", schema: schema)
assert error.reason == :invalid_format
assert error.value == "hello"
Expand Down