Using Cachex in Phoenix - working example?

it does blow up with a bang.. so a bit more defensive code is needed, unless you are doing bangs on purpose..

if you simply remove the bang and use get_by it will return nil on not found, and that will be cached - depending on your caching strategy you might not want that - and you can use the ignore feature.. that way the nil/not found is not cached and the db is always queried on slugs that are not found - but it all depends..

here is an example.. using :ignore so the nil is not cached.. else just remove the bang in get_by

  def get_cached_thing!(slug) do
    Cachex.get(
      :my_cache,
      slug,
      fallback: fn slug ->
        case result = Repo.get_by(Mything, id: slug) do
          %Mything{} ->
            # happy path - commit to cache
            {:commit, result}

          nil ->
            # not found - ignore tuple so it's not cached
            {:ignore, nil}
        end
      end
    )
    |> case do
      # It's not common to return error strings, rather you'd probably want an error tuple
      {:error, _} ->
        {:error, "error - devops needed?"}

      # the ignore returns an :loaded tuple - so match nil
      {:loaded, nil} ->
        {:error, :not_found}

      {success, result} when success in [:ok, :loaded] ->
        {:ok, result}
    end
  end