我正在尝试使用REST创建Phoenix API而不使用Ecto或早午餐。
使用参数在路由器/控制器中创建post函数的语法是什么,但不使用Ecto?
例如在Ruby / Sinatra中,它看起来像这样:
post "/v1/ipf" do
@weight1 = params[:weight1]
@weight2 = params[:weight2]
@weight3 = params[:weight3]
@weight4 = params[:weight4]
@goal1_percent = params[:goal1_percent]
@goal2_percent = params[:goal2_percent]
# etc...
end
更新
根据尼克的回答,这就是我最终的结果:
rest_api /网络/ router.ex:
defmodule RestApi.Router do
use RestApi.Web, :router
pipeline :api do
plug :accepts, ["json"]
end
scope "/", RestApi do
pipe_through :api
scope "/v1", V1, as: :v1 do
get "/ipf", IPFController, :ipf
end
end
end
rest_api /网络/控制器/ V1 / ipf_controller.ex:
defmodule RestApi.V1.IPFController do
use RestApi.Web, :controller
import IPF
def ipf(conn, params) do
{weight1, _} = Integer.parse(params["weight1"])
{weight2, _} = Integer.parse(params["weight2"])
{weight3, _} = Integer.parse(params["weight3"])
{weight4, _} = Integer.parse(params["weight4"])
{goal1_percent, _} = Float.parse(params["goal1_percent"])
{goal2_percent, _} = Float.parse(params["goal2_percent"])
results = IPF.ipf(weight1, weight2, weight3, weight4, goal1_percent, goal2_percent)
render conn, results: results
end
end
rest_api /网络/视图/ V1 / ipf_view.ex:
defmodule RestApi.V1.IPFView do
use RestApi.Web, :view
def render("ipf.json", %{results: results}) do
results
end
end
答案 0 :(得分:4)
Ecto和Brunch与凤凰处理POST没有任何关系。 Brunch是一个Web资产构建工具,Ecto是一个数据库层。
要添加此新路由,您只需在路由器中为新路由添加一个条目:
post "/v1/spf", SPFController, :spf
然后创建控制器:
defmodule MyModule.SPFController do
def spf(conn, params) do
# do whatever
end
end
就是这样。