Skip to content

Commit

Permalink
Add a put behaviour to transport cache
Browse files Browse the repository at this point in the history
  • Loading branch information
vdegove committed Jan 28, 2025
1 parent 974ce2f commit 437d167
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
20 changes: 17 additions & 3 deletions apps/transport/lib/transport/cache.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ defmodule Transport.Cache do
@moduledoc """
This behaviour defines the API for caching, with alternative implementations.
"""

@callback fetch(cache_key :: binary(), fun(), integer()) :: any

defp impl, do: Application.get_env(:transport, :cache_impl)

def fetch(cache_key, comp_fn, expire_value \\ :timer.seconds(60)), do: impl().fetch(cache_key, comp_fn, expire_value)

@callback put(cache_key :: binary(), any(), integer()) :: {:ok | :error, boolean()}

def put(cache_key, value, expire_value \\ :timer.seconds(60)), do: impl().put(cache_key, value, expire_value)

defp impl, do: Application.get_env(:transport, :cache_impl)
end

defmodule Transport.Cache.Cachex do
Expand Down Expand Up @@ -82,6 +85,15 @@ defmodule Transport.Cache.Cachex do
end
end

def put(cache_key, value, expire_value \\ :timer.seconds(60)) do
Cachex.put(
cache_name(),
cache_key,
value,
ttl: expire_value
)
end

def cache_name, do: Transport.Application.cache_name()
end

Expand All @@ -92,4 +104,6 @@ defmodule Transport.Cache.Null do
@behaviour Transport.Cache

def fetch(_cache_key, value_fn, _expire_value), do: value_fn.()

def put(_cache_key, _value, _expire_value), do: {:ok, true}
end
5 changes: 2 additions & 3 deletions apps/transport/lib/transport/preemptive_api_cache.ex
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,10 @@ defmodule Transport.PreemptiveAPICache do
def populate_cache do
Logger.info("[preemptive-api-cache] Populating cache for /api/datasets…")

Cachex.put(
Transport.Application.cache_name(),
Transport.Cache.put(
"api-datasets-index",
TransportWeb.API.DatasetController.prepare_datasets_index_data(),
ttl: @cache_ttl
@cache_ttl
)

Logger.info("[preemptive-api-cache] Finished populating cache for /api/datasets.")
Expand Down

0 comments on commit 437d167

Please sign in to comment.