From 241bee239e4547be768eadd375e6431366b7b949 Mon Sep 17 00:00:00 2001 From: Eugene Pirogov Date: Mon, 3 Oct 2022 11:21:34 +0200 Subject: [PATCH] Implement casing of "byte" string type According to OpenAPI spec v3.1, strings of format "byte" contain base64-encoded values --- lib/open_api_spex/cast/string.ex | 10 ++++++++++ test/cast/string_test.exs | 10 ++++++++++ 2 files changed, 20 insertions(+) diff --git a/lib/open_api_spex/cast/string.ex b/lib/open_api_spex/cast/string.ex index d10fd03e..6820c04c 100644 --- a/lib/open_api_spex/cast/string.ex +++ b/lib/open_api_spex/cast/string.ex @@ -30,6 +30,16 @@ defmodule OpenApiSpex.Cast.String do end end + def cast(%{value: value, schema: %{format: :byte}} = ctx) when is_binary(value) do + case Base.decode64(value) do + {:ok, _} = result -> + result + + _ -> + Cast.error(ctx, {:invalid_format, :base64}) + end + end + @uuid_valid_characters [ ?0, ?1, diff --git a/test/cast/string_test.exs b/test/cast/string_test.exs index fdd4f033..b22e7f84 100644 --- a/test/cast/string_test.exs +++ b/test/cast/string_test.exs @@ -50,6 +50,16 @@ defmodule OpenApiSpex.CastStringTest do assert error.format == :date end + test "string with format (byte)" do + schema = %Schema{type: :string, format: :byte} + date_string = Base.encode64("hello") + assert {:ok, "hello"} = cast(value: date_string, schema: schema) + assert {:error, [error]} = cast(value: "not-a-base64-string", schema: schema) + assert error.reason == :invalid_format + assert error.value == "not-a-base64-string" + assert error.format == :base64 + end + test "casts a string with valid uuid format" do schema = %Schema{type: :string, format: :uuid}