# `ExResilience.Cache`
[🔗](https://github.com/joshrotenberg/ex_resilience/blob/v0.4.0/lib/ex_resilience/cache.ex#L1)

GenServer-based caching layer with pluggable backends.

Caches successful results of function calls, keyed by a caller-provided key.
On cache hit the function is not executed. Errors pass through uncached.

## Options

  * `:name` -- required. Registered name for this cache instance.
  * `:backend` -- module implementing `ExResilience.Cache.Backend`.
    Default: `ExResilience.Cache.EtsBackend`.
  * `:ttl` -- default TTL in milliseconds for cached entries.
    Default: `nil` (no expiry).

Backend-specific options are passed through to `backend.init/1`.

## Examples

    iex> opts = [name: :doc_cache, ttl: 5_000]
    iex> {:ok, _} = ExResilience.Cache.start_link(opts)
    iex> ExResilience.Cache.call(:doc_cache, :my_key, fn -> {:ok, 42} end)
    {:ok, 42}
    iex> ExResilience.Cache.call(:doc_cache, :my_key, fn -> raise "not called" end)
    {:ok, 42}

# `option`

```elixir
@type option() ::
  {:name, atom()} | {:backend, module()} | {:ttl, non_neg_integer() | nil}
```

# `call`

```elixir
@spec call(atom(), term(), (-&gt; term())) :: term()
```

Looks up `key` in the cache. On miss, executes `fun` and caches
a successful result.

Successful results are `{:ok, _}` tuples or any non-error value.
Error results (`{:error, _}` or `:error`) are returned without caching.

## Examples

    ExResilience.Cache.call(:my_cache, "user:1", fn ->
      {:ok, fetch_user(1)}
    end)

# `child_spec`

Returns a specification to start this module under a supervisor.

See `Supervisor`.

# `invalidate`

```elixir
@spec invalidate(atom(), term() | nil) :: :ok
```

Removes the cached entry for `key`.

Pass `nil` to clear all entries.

# `start_link`

```elixir
@spec start_link([option() | {atom(), term()}]) :: GenServer.on_start()
```

Starts a cache process.

See module docs for available options.

# `stats`

```elixir
@spec stats(atom()) :: map()
```

Returns backend statistics for this cache instance.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
