diff --git a/lib/mbta_v3_api/repository.ex b/lib/mbta_v3_api/repository.ex index 359d67ac..31de1b9c 100644 --- a/lib/mbta_v3_api/repository.ex +++ b/lib/mbta_v3_api/repository.ex @@ -60,28 +60,32 @@ defmodule MBTAV3API.Repository.Impl do use Nebulex.Caching.Decorators - alias MBTAV3API.JsonApi + alias MBTAV3API.{JsonApi, RepositoryCache} @ttl :timer.hours(1) @impl true + @decorate cacheable(cache: RepositoryCache, on_error: :nothing, opts: [ttl: @ttl]) def route_patterns(params, opts \\ []), do: all(MBTAV3API.RoutePattern, params, opts) @impl true + @decorate cacheable(cache: RepositoryCache, on_error: :nothing, opts: [ttl: @ttl]) def routes(params, opts \\ []), do: all(MBTAV3API.Route, params, opts) @impl true + @decorate cacheable(cache: RepositoryCache, on_error: :nothing, opts: [ttl: @ttl]) def schedules(params, opts \\ []), do: all(MBTAV3API.Schedule, params, opts) @impl true + @decorate cacheable(cache: RepositoryCache, on_error: :nothing, opts: [ttl: @ttl]) def stops(params, opts \\ []), do: all(MBTAV3API.Stop, params, opts) @impl true + @decorate cacheable(cache: RepositoryCache, on_error: :nothing, opts: [ttl: @ttl]) def trips(params, opts \\ []), do: all(MBTAV3API.Trip, params, opts) @spec all(module(), JsonApi.Params.t(), Keyword.t()) :: {:ok, JsonApi.Response.t(JsonApi.Object.t())} | {:error, term()} - @decorate cacheable(cache: MBTAV3API.RepositoryCache, on_error: :nothing, opts: [ttl: @ttl]) defp all(module, params, opts) do params = JsonApi.Params.flatten_params(params, module) url = "/#{JsonApi.Object.plural_type(module.jsonapi_type())}" diff --git a/lib/mbta_v3_api/repository_cache.ex b/lib/mbta_v3_api/repository_cache.ex index 375db854..7a362c15 100644 --- a/lib/mbta_v3_api/repository_cache.ex +++ b/lib/mbta_v3_api/repository_cache.ex @@ -2,5 +2,23 @@ defmodule MBTAV3API.RepositoryCache do @moduledoc """ Cache used to reduce the number of calls to the V3 API. """ - use Nebulex.Cache, otp_app: :mobile_app_backend, adapter: Nebulex.Adapters.Local + use Nebulex.Cache, + otp_app: :mobile_app_backend, + adapter: Nebulex.Adapters.Local, + default_key_generator: __MODULE__ + + @behaviour Nebulex.Caching.KeyGenerator + + @impl Nebulex.Caching.KeyGenerator + def generate(mod, fun, []) do + "#{mod}|#{fun}" + end + + def generate(mod, fun, [arg]) do + "#{mod}|#{fun}|#{:erlang.phash2(arg)}" + end + + def generate(mod, fun, args) do + "#{mod}|#{fun}|#{:erlang.phash2(args)}" + end end