在 Phoenix 中幂等地创建用户

Idempotently creating a user in Phoenix

我想使用 Phoenix 的开箱即用功能 create/2 将其用于我的用户注册用例。为此,我需要幂等地创建一个用户。我在 Elixir 中找不到最惯用的方法来做到这一点。

例如,这是 Phoenix 用于创建资源(在本例中为用户)的开箱即用代码段:

case Repo.insert(changeset) do
  {:ok, user} ->
    conn
    |> put_status(:created)
    |> put_resp_header("location", user_path(conn, :show, user))
    |> render("show.json", user: user)
  {:error, changeset} ->
    conn
      |> put_status(:unprocessable_entity)
      |> render(BrewswapApi.ChangesetView, "error.json", changeset: changeset)
end

我想做的是首先通过特定字段检查用户是否存在。如果存在,则 return 带有对象的 200 否则 运行 上面的代码。

我会为此使用嵌套的 case 语句吗?

使用功能插件 return 现有用户

这是使用 function plugs. You can see in the example how they transformed the show action from multiple nested cases to using plugs. Note the use of halt/1 来阻止请求向下游处理的一个很好的例子。

但是我看到 return注册现有用户实例失败是一个安全问题。如果 "field" 已经被占用,最好 return 一个错误。

使用唯一约束 return 错误

为此,由于 "field" 对用户而言必须是唯一的,因此您需要创建一个 unique_index,然后在 changeset 中定义一个 unique_constraint

现在在您的 create 操作中,如果您尝试插入具有重复 "field" 的用户,changeset 将无效并且来自 {:error, changeset} 的块将 运行.