2017-11-11 223 views
0

結果使用PorcelainHTTPoison我想做到以下幾點:啓動節點過程中靈藥然後返回一個HTTP請求

  • 啓動節點服務器

  • 發送一個HTTP請求到節點過程

  • 關閉過程

  • 回報次的結果E分別請求

我一直在試圖像下面的內容:

require HTTPoison 
alias Porcelain.Process, as: Proc 
alias Porcelain.Result, as: Res 


def request do 
    cmd = "node node_app/src/index.js" 
    opts = [out: {:send, self()}] 
    proc = %Proc{pid: pid} = Porcelain.spawn_shell(cmd, opts) 

    receive do 
    {^pid, :data, :out, log} -> 
     IO.puts "Node log => #{log}" 
     # only if log contains "running" should I send the request 
     if String.contains?(log, "running") do 
     IO.puts "Requesting..." 
     %HTTPoison.Response{body: body} = HTTPoison.get! @root_url <> "/collection" 
     Proc.stop(proc) 
     end 
    {^pid, :result, %Res{status: status} = res} -> 
     nil 
    end 

    Proc.await proC# wait for the process to terminate 
    body # return body of request 
end 

的一個問題是,我沒有對的時候我可以返回了的接收控制。

我得到了一個靈丹妙藥的警告,表明身體可能沒有被定義,我想避免。

我該怎麼做呢?有沒有更好的方法來做到這一點?

在此先感謝您的幫助

回答

1

有兩個毛刺與此代碼:首先,應該在任何情況下停止衍生的進程。

次要的,你應該把整個結果receive綁定到變量上。像這樣的東西應該工作(未經測試):

result = receive do 
    {^pid, :data, :out, log} -> 
    IO.puts "Node log => #{log}" 
    # only if log contains "running" should I send the request 
    if String.contains?(log, "running") do 
     IO.puts "Requesting..." 
     HTTPoison.get! @root_url <> "/collection" 
    end 
    {^pid, :result, %Res{status: status} = res} -> 
    nil 
end 

Proc.stop(proc) 

with %HTTPoison.Response{body: body} <- result, do: body 

最後Kernel.SpecialForms.with/1將有效地返回什麼,如果匹配成功不匹配預期Response,或body


旁註:警告的確是未來的運行時錯誤。 bodyreceive的範圍內定義,使其在關閉範圍內不可見。