2016-11-30 38 views
0

我想在Maru中定義一個自定義類型並使用它來解析JSON post實體,並使用它進一步執行sql語句。但我不確定如何繼續。在Elixir中定義一個自定義的Maru類型並使用它來獲取Json POST實體


這裏是我的自定義類型

defmodule Maru.Types.Volume do 
    use Maru.Type 

    @type length :: Float 
    @type breadth :: Float 
    @type height :: Float 

end 

這種類型在路由器

defmodule My.Router.Box do 
    use Maru.Router 
    alias My.Repo.Box, as: :DB 

    namespace :select_volume do 
     params do 
     requires :volume, type: Volume 

    post do 
     volume = DB.getBoxWithRequiredVolume(params) 
     conn |> put_status(200) |> json(volume) 
    end 
end 

然後在這裏使用SQL查詢

defmodule My.Repo.Box do 
    import Ecto.Query 
    require Logger 

    def getBoxWithRequiredVolume(params) do 
     volume = params[:volume] 
     query = from box in My.Box, 
      select: (
       %{id: box.id} 
     ), 
      where: (box.length == ^volume[:length] and box.breadth == ^volume[:breadth] and box.height == ^volume[:height]) 
     query |> My.Repo.all 
    end 
end 

這是使用REST查詢的實體:

http://localhost:8880/select_volume 
{ 
"volume":{ 
    "length": 20, 
    "breadth": 5, 
    "height": 5 
} 
} 

錯誤:

%Maru.Exceptions.InvalidFormatter{param: :volume, reason: :illegal, 
value: %{"breadth" => 5, "height" => 5, "length" => 20}} 
+0

你的問題是什麼? – mudasobwa

+0

上面的代碼不起作用。我無法使用捲來分析實體 –

+0

這仍然不是問題。另外,你是否收到任何錯誤?怎麼了?請根據本網站的規則重新提出您的問題,否則將被關閉。 – mudasobwa

回答

0

String小號又名binariesAtom s爲沒有仙丹一樣。

您傳遞的值具有二進制文件,因爲它是鍵。格式化程序期望原子(例如:volume[:length])。

此外,我建議你有一個明確的測試My.Repo.Box.getBoxWithRequiredVolume確保它返回所期望的。


旁註:這種特定拋出異常可能流下了光的源代碼:這是Maru.Runtime.do_parse/3

0

,你需要的不是一個自定義類型,你只需要讓你的PARAMS是這樣的:從你上面發送的請求%{breadth: 5.0, height: 5.0, length: 20.0}

params do 
    requires :volume, type: Map do 
    requires :length, type: Float 
    requires :breadth, type: Float 
    requires :height, type: Float 
    end 
end 

,然後,你可以得到params與價值。

相關問題