Have you tried manually calling the function in iex
? And then do several Cachex.ttl
calls and see if the TTL value is decreasing?
I think your problem is that you are calling Cachex.expire inside fetch function and key not be created until you exit that function, It should be done this way.
From ttl option of `Cachex.fetch` · Issue #195 · whitfin/cachex · GitHub
with { :commit, _val } ← Cachex.fetch(:my_cache, cache_key, &my_func/1) do
Cachex.expire(:my_cache, cache_key, :timer.seconds(1)
{ :commit, val }
end
That sounds correct to me. You can also add it to the existing case statement:
Cachex.fetch(:github, "avatar_url", fn() ->
# ...
|> case do
{:error, _} -> nil
{_, nil} -> {:error, :not_found}
{success, result} when success in [:ok, :loaded, :commit] ->
if success == :commit, do: Cachex.expire(:github, "avatar_url", :timer.minutes(5))
result
end
Just an off-topic comment about that case statement: it seems to me that it does not make much sense that you turn {:error, _}
to nil
but you return {:error, :not_found}
if the result is nil
. I would try to be consistent there and either return nil
or {:error, cause}
in both cases, whatever is appropriate.