Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Erlang Phoenix解析API参数_Erlang_Elixir_Phoenix Framework - Fatal编程技术网

Erlang Phoenix解析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

我正在尝试清理这个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

您不需要对所有内容进行模式匹配。我同意:

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)”作为您的第一个建议契约。只需拆下防护装置,这在那里有点多余。