Hello.
I’d like to send a request in Task.start_link/1
, but my code does not work.
def create(conn, params) do
file_path = unless params["image"] == "" do
uuid = SecureRandom.uuid()
File.cp(params["image"].path, "./static/image/tmp/#{uuid}.jpg")
"./static/image/tmp/"<>uuid<>".jpg"
else
"./static/image/stones.png"
end
map =
@db_domain_url <> @api_url <> @tournament_url
|> send_tournament_multipart(params, file_path)
# first task
Task.start_link(fn ->
map["data"]["followers"]
|> Enum.each(fn follower ->
follower["id"]
|> Accounts.get_devices_by_user_id()
|> Enum.each(fn device ->
Notifications.push(follower["name"]<>"さんが大会を予定しました。", device.device_id)
end)
end)
end)
# second task
Task.start_link(fn ->
event_time =
map["data"]["event_date"]
|> Timex.parse!("{ISO:Extended}")
|> DateTime.to_unix()
now =
DateTime.utc_now()
|> DateTime.to_unix()
IO.inspect(event_time - now)
Process.sleep((event_time - now)*1000)
response =
@db_domain_url <> @api_url <> @get_tournament_info_url
|> IO.inspect(label: :url)
|> send_json(%{"tournament_id" => map["data"]["id"]})
response["data"]["entrants"]
|> Enum.each(fn entrant ->
entrant["id"]
|> Accounts.get_devices_by_user_id()
|> Enum.each(fn device ->
Notifications.push(response["data"]["name"]<>"がスタートしました!", device.device_id)
end)
end)
IO.inspect({"finished sending notifications"})
end)
unless params["image"] == "" do
File.rm(file_path)
end
json(conn, map)
end
In this function, it sends a multipart/form-data
request to another server. The response should be json and the first task
works properly.
But the second task
throws an error when it runs send_json/1
.
This is the source code of send_json/1
below.
defmodule Common.Tools do
use Timex
defmacro __using__(_opts) do
quote do
def send_json(url, params) do
content_type = [{"Content-Type", "application/json"}]
IO.inspect(params, label: :params)
p = if is_binary(params) do
params
else
Poison.encode!(params)
end
|> IO.inspect(label: :encode)
with {:ok, attrs} <- Poison.decode(p) |> IO.inspect,
{:ok, response} <- HTTPoison.post(url, attrs, content_type),
{:ok, body} <- Poison.decode(response.body) do
body
else
{:error, {reason, _, _}} ->
%{
"result" => false,
"reason" => reason
}
{:error, reason} ->
%{
"result" => false,
"reason" => reason
}
_ ->
%{
"result" => false,
"reason" => "Unexpected error"
}
end
end
...
end
And the error is this;
url: "http://localhost:4000/api/tournament/get"
params: %{"tournament_id" => 17}
encode: "{\"tournament_id\":17}"
{:ok, %{"tournament_id" => 17}}
[error] Task #PID<0.685.0> started from #PID<0.675.0> terminating
** (stop) {{:case_clause, %{"tournament_id" => 17}}, []}
Function: #Function<2.33228726/0 in PappapWeb.TournamentController.create/2>
Args: []
I’m wondering that HTTPoison.post/3
cannot be executed in asynchronous function… (though I don’t know what the truth is)
If you know something of this, please let me know