Update the FetchJsons to allow use a function to transform the data.

dev
KKlochko 5 months ago
parent 57ead52ba2
commit d398cc1594

@ -1,13 +1,10 @@
defmodule DecentralisedBookIndex.Sync.ApiClients.FetchJsons do defmodule DecentralisedBookIndex.Sync.ApiClients.FetchJsons do
alias DecentralisedBookIndex.Sync.ApiClients.FetchJsons
alias DecentralisedBookIndex.Sync.ApiClients.FetchJson alias DecentralisedBookIndex.Sync.ApiClients.FetchJson
def get(url) do require Logger
case FetchJson.get(url) do
{:ok, data} ->
[]
{:error, message} -> {:error, message}
end
def get(url, mapper \\ &FetchJsons.get_data/1) do
query_results = query_results =
Stream.resource( Stream.resource(
# Initial state: # Initial state:
@ -20,9 +17,9 @@ defmodule DecentralisedBookIndex.Sync.ApiClients.FetchJsons do
next -> next ->
case FetchJson.get(next) do case FetchJson.get(next) do
{:ok, page} -> {:ok, page} ->
{page["data"], get_in(page, ["links", "next"])} {mapper.(page["data"]), get_in(page, ["links", "next"])}
{:error, message} -> {:error, message} ->
Logger.error("FetchJsons error: #{inspect(message)}") Logger.error("FetchJsons error for #{url}: #{inspect(message)}")
{[], nil} {[], nil}
end end
end, end,
@ -32,4 +29,8 @@ defmodule DecentralisedBookIndex.Sync.ApiClients.FetchJsons do
{:ok, query_results} {:ok, query_results}
end end
def get_data(data) do
data
end
end end

@ -17,5 +17,21 @@ defmodule DecentralisedBookIndex.Sync.ApiClients.FetchJsonsTest do
assert {:ok, records} = FetchJsons.get("#{@test_server_endpoint}/api/v1/json/author") assert {:ok, records} = FetchJsons.get("#{@test_server_endpoint}/api/v1/json/author")
assert length(records) == 11 assert length(records) == 11
end end
test "get authors names from API" do
for number <- 1..11 do
Metadata.create_author!("Author#{number}", "An description#{number}")
end
get_author_names = fn data ->
Enum.map(data, fn author -> author["attributes"]["name"] end)
end
assert {:ok, records} =
FetchJsons.get("#{@test_server_endpoint}/api/v1/json/author", get_author_names)
assert length(records) == 11
assert Enum.all?(records, fn author -> String.contains?(author, "Author") end)
end
end end
end end

Loading…
Cancel
Save