/
memcachex.ex
81 lines (65 loc) · 2.39 KB
/
memcachex.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
if Code.ensure_loaded?(Memcache) do
defmodule Mnemonix.Stores.Memcachex do
@moduledoc """
A `Mnemonix.Store` that uses Memcachex to store state in memcached.
iex> {:ok, store} = Mnemonix.Stores.Memcachex.start_link
iex> Mnemonix.put(store, "foo", "bar")
iex> Mnemonix.get(store, "foo")
"bar"
iex> Mnemonix.delete(store, "foo")
iex> Mnemonix.get(store, "foo")
nil
This store throws errors on the functions in `Mnemonix.Features.Enumerable`.
"""
defmodule Exception do
defexception [:message]
end
use Mnemonix.Store.Behaviour
use Mnemonix.Store.Translator.Term
alias Mnemonix.Store
####
# Mnemonix.Store.Behaviours.Core
##
@doc """
Connects to memcached to store data using provided `opts`.
- `initial:` A map of key/value pairs to ensure are set in memcached at boot.
- *Default:* `%{}`
All other options are passed verbatim to `Memcache.start_link/1`.
"""
@spec setup(Mnemonix.Store.options)
:: {:ok, state :: term} | {:stop, reason :: any}
def setup(opts) do
options = opts
|> Keyword.put(:coder, Memcache.Coder.Erlang)
Memcache.start_link(options)
end
####
# Mnemonix.Store.Behaviours.Map
##
@spec delete(Mnemonix.Store.t, Mnemonix.key)
:: {:ok, Mnemonix.Store.t} | Mnemonix.Store.Behaviour.exception
def delete(store = %Store{state: conn}, key) do
case Memcache.delete(conn, key) do
{:ok} -> {:ok, store}
{:error, reason} -> {:raise, Exception, [reason: reason]}
end
end
@spec fetch(Mnemonix.Store.t, Mnemonix.key)
:: {:ok, Mnemonix.Store.t, {:ok, Mnemonix.value} | :error} | Mnemonix.Store.Behaviour.exception
def fetch(store = %Store{state: conn}, key) do
case Memcache.get(conn, key) do
{:error, "Key not found"} -> {:ok, store, :error}
{:ok, value} -> {:ok, store, {:ok, value}}
{:error, reason} -> {:raise, Exception, [reason: reason]}
end
end
@spec put(Mnemonix.Store.t, Mnemonix.key, Store.value)
:: {:ok, Mnemonix.Store.t} | Mnemonix.Store.Behaviour.exception
def put(store = %Store{state: conn}, key, value) do
case Memcache.set(conn, key, value) do
{:ok} -> {:ok, store}
{:error, reason} -> {:raise, Exception, [reason: reason]}
end
end
end
end