|
| 1 | +defmodule Atex.Lexicon.Validators do |
| 2 | + alias Atex.Lexicon.Validators |
| 3 | + |
| 4 | + @type blob_option() :: {:accept, list(String.t())} | {:max_size, integer()} |
| 5 | + |
| 6 | + @type blob_t() :: |
| 7 | + %{ |
| 8 | + "$type": String.t(), |
| 9 | + req: %{"$link": String.t()}, |
| 10 | + mimeType: String.t(), |
| 11 | + size: integer() |
| 12 | + } |
| 13 | + | %{} |
| 14 | + |
| 15 | + @spec string(list(Validators.String.option())) :: Peri.custom_def() |
| 16 | + def string(options \\ []), do: {:custom, {Validators.String, :validate, [options]}} |
| 17 | + |
| 18 | + @spec integer(list(Validators.Integer.option())) :: Peri.custom_def() |
| 19 | + def integer(options \\ []), do: {:custom, {Validators.Integer, :validate, [options]}} |
| 20 | + |
| 21 | + @spec array(Peri.schema_def(), list(Validators.Array.option())) :: Peri.custom_def() |
| 22 | + def array(inner_type, options \\ []) do |
| 23 | + {:ok, ^inner_type} = Peri.validate_schema(inner_type) |
| 24 | + {:custom, {Validators.Array, :validate, [inner_type, options]}} |
| 25 | + end |
| 26 | + |
| 27 | + @spec blob(list(blob_option())) :: Peri.schema_def() |
| 28 | + def blob(options \\ []) do |
| 29 | + options = Keyword.validate!(options, accept: nil, max_size: nil) |
| 30 | + accept = Keyword.get(options, :accept) |
| 31 | + max_size = Keyword.get(options, :max_size) |
| 32 | + |
| 33 | + mime_type = |
| 34 | + {:required, |
| 35 | + if(accept, |
| 36 | + do: {:string, {:regex, strings_to_re(accept)}}, |
| 37 | + else: {:string, {:regex, ~r"^.+/.+$"}} |
| 38 | + )} |
| 39 | + |
| 40 | + { |
| 41 | + :either, |
| 42 | + { |
| 43 | + # Newer blobs |
| 44 | + %{ |
| 45 | + "$type": {:required, {:literal, "blob"}}, |
| 46 | + ref: {:required, %{"$link": {:required, :string}}}, |
| 47 | + mimeType: mime_type, |
| 48 | + size: {:required, if(max_size != nil, do: {:integer, {:lte, max_size}}, else: :integer)} |
| 49 | + }, |
| 50 | + # Old deprecated blobs |
| 51 | + %{ |
| 52 | + cid: {:reqiured, :string}, |
| 53 | + mimeType: mime_type |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + end |
| 58 | + |
| 59 | + @spec boolean_validate(boolean(), String.t(), keyword() | map()) :: |
| 60 | + Peri.validation_result() |
| 61 | + def boolean_validate(success?, error_message, context \\ []) do |
| 62 | + if success? do |
| 63 | + :ok |
| 64 | + else |
| 65 | + {:error, error_message, context} |
| 66 | + end |
| 67 | + end |
| 68 | + |
| 69 | + @spec strings_to_re(list(String.t())) :: Regex.t() |
| 70 | + defp strings_to_re(strings) do |
| 71 | + strings |
| 72 | + |> Enum.map(&String.replace(&1, "*", ".+")) |
| 73 | + |> Enum.join("|") |
| 74 | + |> then(&~r/^(#{&1})$/) |
| 75 | + end |
| 76 | +end |
0 commit comments