Skip to content

Instantly share code, notes, and snippets.

@WillsonSmith
Created January 3, 2017 04:37
Show Gist options
  • Save WillsonSmith/e3d406b511573601e1423e2b1e97eaf4 to your computer and use it in GitHub Desktop.
Save WillsonSmith/e3d406b511573601e1423e2b1e97eaf4 to your computer and use it in GitHub Desktop.
import IO
defmodule SimilarfilmsPhoenix.GetData do
def build_key(key) do
transforms = %{"id" => "movie_id", "vote_average" => "rating", "poster_path" => "image_url"}
if (transforms[key]) do
transforms[key]
else
key
end
end
def transform_api_results({key, val}, acc) do
Map.put(acc, build_key(key), val)
end
def get_data(path) do
database_movies = SimilarfilmsPhoenix.Repo.all(SimilarfilmsPhoenix.Movie)
|> Enum.map(fn(movie) -> Map.from_struct(movie) end)
|> Enum.map(fn(movie) -> Enum.reduce(movie, %{}, fn({key, val}, acc) -> Map.put(acc, Atom.to_string(key), val) end) end)
HTTPotion.start
api = Application.get_env(:similarfilms_phoenix, SimilarfilmsPhoenix.ApiKey)[:moviedb_api_key]
host = "api.themoviedb.org"
api_results = HTTPotion.get("https://#{host}/#{path}", query: %{"api_key": api})
|> Map.get(:body)
|> Poison.decode!
transformed_results = api_results["results"]
|> Enum.map(fn(movie) -> Enum.reduce(movie, %{}, &transform_api_results/2) end)
transformed_results || []
# database_movies
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment