2017-05-25 69 views
1

我試圖清理這個API端點。有什麼方法可以將參數放入模型中?Phoenix解析API參數

def listen conn, %{"messages" => [%{"body" => body, "chatId" => chatId, "chatType" => chatType, "from" => from, "id" => id, "mention" => mention, "participants" => participants, "readReceiptRequested" => readReceiptRequested, "timestamp" => timestamp, "type" => type}]} do 
    sendMessage chatId, from, body 
    json conn, 200 
end 

回答

1

你不需要模式匹配所有東西。我會去的:

def do_send %{"chatId" => chatId, 
       "body" => body, 
       "from" => from} = _message, 
    do: sendMessage chatId, from, body 

def listen conn, %{"messages" => messages} do 
    Enum.each(messages, &do_send/1) 
    json conn, 200 
end 

,或者相反,人們可能更erlangish方法做:

def listen conn, %{"messages" => []} do 
    json conn, 200 
end 

def listen conn, %{"messages" => [message|messages]} do 
    with %{"chatId" => chatId, 
     "body" => body, 
     "from" => from} <- message, 
    do: sendMessage chatId, from, body 

    listen(conn, %{"messages" => messages}) 
end 
+0

我得到了「不能調用本地當/ 2匹配內容,稱爲:%{」messages「=> messages}當:erlang.is_list(messages)」爲您的第一個建議 –

+0

確實。只要取下警衛,在那裏就顯得多餘了。 – mudasobwa

0

你可以試試這個,如果希望多封郵件:

def listen(conn, %{"messages" => messages}) do 
    Enum.each(messages, fn msg -> 
    chatId = msg["chatId"] 
    from = msg["from"] 
    body = msg["body"] 

    sendMessage(chatId, from, body) 
    end) 

    conn 
    |> put_status(200) 
    |> json(%{}) 
end 

或針對單個消息:

def listen(conn, %{"messages" => [msg|messages]}) do 
    chatId = msg["chatId"] 
    from = msg["from"] 
    body = msg["body"] 

    sendMessage(chatId, from, body) 

    conn 
    |> put_status(200) 
    |> json(%{}) 
end