forked from pow-auth/pow
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ets_cache_mock.ex
45 lines (36 loc) · 1.05 KB
/
ets_cache_mock.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
defmodule Pow.Test.EtsCacheMock do
@moduledoc false
@tab __MODULE__
def init, do: :ets.new(@tab, [:set, :protected, :named_table])
def get(config, key) do
ets_key = ets_key(config, key)
@tab
|> :ets.lookup(ets_key)
|> case do
[{^ets_key, value} | _rest] -> value
[] -> :not_found
end
end
def delete(config, key) do
:ets.delete(@tab, ets_key(config, key))
end
def put(config, key, value) do
:ets.insert(@tab, {ets_key(config, key), value})
end
def keys(config) do
namespace = ets_key(config, "")
length = String.length(namespace)
Stream.resource(
fn -> :ets.first(@tab) end,
fn :"$end_of_table" -> {:halt, nil}
previous_key -> {[previous_key], :ets.next(@tab, previous_key)} end,
fn _ -> :ok
end)
|> Enum.filter(&String.starts_with?(&1, namespace))
|> Enum.map(&String.slice(&1, length..-1))
end
defp ets_key(config, key) do
namespace = Pow.Config.get(config, :namespace, "cache")
"#{namespace}:#{key}"
end
end