I’m currently learning elixir and thus am facing problem in fetching data from multiple URLs with the help of HTTPoison, then bundling up all the response and sending them back. I’m using Phoenix as my server.
Basically I want to get the data from these URLs:
http://jsonplaceholder.typicode.com/posts
http://jsonplaceholder.typicode.com/comments
http://jsonplaceholder.typicode.com/photos
http://jsonplaceholder.typicode.com/users
And then bundle up the response like:
json conn, %{"success": true, "users": users, "posts": posts, "comments": comments, "photos": photos}
And send it back to the client
I tried looking into Issue #108 but was unable to figure out how to handle async requests. I was successfully able to get for sync request using:
def index(conn, %{"url" => url}) do
case HTTPoison.get(url) do
{:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
json conn, %{"success": true, "body": body}
{:ok, %HTTPoison.Response{status_code: 404}} ->
json conn, %{"success": false, "body": "Not Found"}
{:error, %HTTPoison.Error{reason: reason}} ->
IO.inspect reason
json conn, %{"success": false}
_ ->
json conn, %{"success": true, "reason": "Other Status Code"}
end
end