-
-
Notifications
You must be signed in to change notification settings - Fork 181
/
url_encoded_binary.ex
51 lines (39 loc) · 1.08 KB
/
url_encoded_binary.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
defmodule Ash.Type.UrlEncodedBinary do
@moduledoc """
Represents a binary that attempts to decode input strings as a url encoded base64 string.
A builtin type that can be referenced via `:url_encoded_binary`
"""
use Ash.Type
@impl true
def storage_type, do: :binary
@impl true
def generator(_constraints) do
base64 =
[?A..?Z, ?a..?z, ?0..?9, ?+, ?/]
|> StreamData.string()
|> StreamData.map(&Base.encode64/1)
StreamData.one_of([StreamData.binary(), base64])
end
@impl true
def cast_input(value, _) when is_binary(value) do
case Base.url_decode64(value, padding: false) do
{:ok, decoded} ->
Ecto.Type.cast(:binary, decoded)
:error ->
Ecto.Type.cast(:binary, value)
end
end
def cast_input(value, _) do
Ecto.Type.cast(:binary, value)
end
@impl true
def cast_stored(nil, _), do: {:ok, nil}
def cast_stored(value, _) do
Ecto.Type.load(:binary, value)
end
@impl true
def dump_to_native(nil, _), do: {:ok, nil}
def dump_to_native(value, _) do
Ecto.Type.dump(:binary, value)
end
end