Erlang Phoenix解析API参数
我正在尝试清理这个API端点。有没有一种方法可以将参数放入模型或其他东西中Erlang Phoenix解析API参数,erlang,elixir,phoenix-framework,Erlang,Elixir,Phoenix Framework,我正在尝试清理这个API端点。有没有一种方法可以将参数放入模型或其他东西中 def listen conn, %{"messages" => [%{"body" => body, "chatId" => chatId, "chatType" => chatType, "from" => from, "id" => id, "mention" => mention, "participants" => participants, "readRecei
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
您不需要对所有内容进行模式匹配。我同意:
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
或者,可以使用更具爱尔兰风格的方法:
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
def listen conn,%{“messages”=>[]}do
康涅狄格州,200
结束
def listen conn,%%{“messages”=>[message | messages]}do
使用%{“chatId”=>chatId,
“body”=>body,
“发件人”=>发件人}邮件})
结束
如果需要多条消息,您可以尝试以下操作:
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
我得到了“无法调用本地when/2内部匹配,称为:%{“messages”=>messages}when:erlang.is_列表(messages)”作为您的第一个建议契约。只需拆下防护装置,这在那里有点多余。