HTTP是文本协议, 传递给服务器的参数全部都是字符串, 要在Elixir中使用, 需要转换为合适的类型. 本文使用Ecto Changset内置的cast/3函数对数据类型进行转换. 使用 validate_* 系列函数对参数的值进行验证. Ecto 相关函数文档为 https://hexdocs.pm/ecto/Ecto....

定义模型

定义一个分页参数验证模型

defmodule TgMhs.Pagination do
  use TgMhs.Web, :model

  @required_fields ~w(direction id from_id to_id chat_type)
  @optional_fields ~w()

  schema "pagination" do
    field :direction, :string
    field :id,        :integer
    field :from_id,   :integer
    field :to_id,     :integer
    field :chat_type, :string
  end

  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
    |> validate_inclusion(:direction, ["middle", "up", "down"])
    |> validate_inclusion(:chat_type, ["peerUser", "peerChat", "peerChannel"])
  end

  def changeset_errors(changeset) do
     changeset.errors
     |> Enum.map(fn {k, v} -> "Parameter #{k} #{render_detail(v)}" end)
  end  
end

在控制器中验证

defmodule TgMhs.HelloController do
  use TgMhs.Web, :controller
  alias TgMhs.Pagination

  def index(conn, params) do
    changeset = Pagination.changeset(%Pagination{}, params)

    case changeset do
      %{:params => %{ 
          "direction" => direction, 
          "id" => id, 
          "from_id" => from_id, 
          "to_id" => to_id, 
          "chat_type" => chat_type
      }, :valid? => true} ->
        conn |> text("OK")
      _ ->
        conn
        |> put_status(400)
        |> text("Error, wrong parameters supplied!")
    end
  end
end

developerworks
1.7k 声望266 粉丝