Skip to content

Instantly share code, notes, and snippets.

@bryansray
Last active September 20, 2016 04:44
Show Gist options
  • Save bryansray/6ad00d0792374fea68f7e64ccc7c1636 to your computer and use it in GitHub Desktop.
Save bryansray/6ad00d0792374fea68f7e64ccc7c1636 to your computer and use it in GitHub Desktop.
# Questions:
# 1. How can I specify that path for the cached item by something other than the URL?
# 2. I'd like to use pieces in the Response to generate the cache location, but then, how do I check if the cached file exists before making the API call?
defmodule Base
use HTTPoison.Base
# ... Basic HTTPoison Implementation ...
end
defmodule API
def get!(url)
Base.API.get!(url)
|> Map.get(:body)
|> Map.new
end
end
defmodule Character
def get!(url), do: API.get!(url)
def get(realm, character), do: get_url(realm, name) |> get!
end
defmodule Guild
def get!(url), do: API.get!(url)
def get(realm, name), do: get_url(realm, name) |> get!
end
# Caching Implementation ... ?
defmodule Exarmory.Cache do
defstruct [:region, :realm, :name]
def get!(module, url, %Exarmory.Cache{ } = cache) do
location = module.storage(cache) <> ".json" |> String.downcase
# OR use URL if module.storage/1 is not provided
case File.read(location) do
{ :ok, content } ->
IO.puts("Found cache ...")
content
{ :error, _ } ->
IO.puts("Making API call ...")
# Exarmory.API.get!(url)
end
end
end
Cache.get!(url)
@DavidAntaramian
Copy link

DavidAntaramian commented Sep 20, 2016

Use Cache.get! as your primary interface instead of API.get!:

defmodule Cache do
  def get!(url) do
    url
    |> cache_file_for_url()
    |> File.read()
    |> handle_file_read(url)
  end

  defp handle_file_read({:error, _}, url) do
    url
    |> API.get!()
    |> cache_result(url)
  end

  defp handle_file_read({:ok, data}, _) do
    data
  end

  defp cache_result(data, url) do
    url
    |> cache_file_for_url()
    |> File.write!(data)

    data
  end

  defp cache_file_for_url(url) do
    cache_location = Application.get_env(:my_app, :http_cache_path)
    filename = Base.url_encode64(url)

    Path.join(cache_location, filename)
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment