sh Elixir Phoenix Cheatsheet

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sh Elixir Phoenix Cheatsheet相关的知识,希望对你有一定的参考价值。

defmodule Dossy.Web.AuthControllerTest do
  use Dossy.Web.ConnCase

  describe "create user" do
    test "registering the user works", %{conn: conn} do
      user_details = %{
        first_name: "John",
        last_name: "Smith",
        email: "john@gmail.com",
        password: "password",
        password_confirmation: "password",
      }

      conn = post(conn, "/v1/auth/register", user: user_details)
    
      assert %{
        "user"=> user_response, 
        "jwt" => token_response, 
        "exp" => _exp_response
      } = json_response(conn, 201)

      %{"id"=> id} = user_response

      conn = conn
        |> recycle()
        |> put_req_header("authorization", "Bearer #{token_response}")

      conn = get(conn, user_path(conn, :show, id))

      assert json_response(conn, 200) == %{
        "id" => id,
        "first_name" => user_details.first_name,
        "last_name" => user_details.last_name,
        "email" => user_details.email,
        "avatar" => nil
      }
    end

    test "does not create user and renders errors when data is invalid", %{conn: conn} do
      user_details = %{
        first_name: nil,
        last_name: "Smith",
        email: "john@gmail.com",
      }

      conn = post(conn, "v1/auth/register", user: user_details)
      errors = json_response(conn, 422)["errors"]
      assert errors != %{}
      assert errors["first_name"], "can't be blank"
    end

    test "passwords must match", %{conn: conn} do
      user_details = %{
        first_name: "John",
        last_name: "Smith",
        email: "john@gmail.com",
        password: "password",
        password_confirmation: "completely different",
      }

      conn = post(conn, "/v1/auth/register", user: user_details)
      errors = json_response(conn, 422)["errors"]
      assert errors != %{}
      assert errors["password_confirmation"] == ["Password does not match"]
    end
  end

  describe "login" do
    test "login with password", %{conn: conn} do
      user = insert(:user)

      session_details = %{
        email: user.email,
        password: "password"
      }
      
      conn = post(conn, "/v1/auth/identity/callback", session_details)
    
      assert %{
        "user"=> user_response, 
        "jwt" => _token_response, 
        "exp" => _exp_response
      } = json_response(conn, 200)

      assert user_response["first_name"] == user.first_name
    end
  end
end
alias Dossy.Accounts

[
  %{
    first_name: "John",
    last_name: "Doe",
    email: "john@test.com",
    password: "password",
    password_confirmation: "password",
    auth_provider: "password"
  },
  %{
    first_name: "Matt",
    last_name: "Platts",
    email: "matt@test.com",
    password: "password",
    password_confirmation: "password",
    auth_provider: "password"
  },
]
|> Enum.map(&Accounts.create_user(&1))
defmodule Dossy.Accounts.User do
  use Ecto.Schema
  import Ecto.Changeset
  alias Dossy.Accounts.User

  schema "accounts_users" do
    field :email, :string
    field :avatar, :string
    field :first_name, :string
    field :last_name, :string
    field :auth_provider, :string
    field :encrypted_password, :string
    field :role, :string

    field :password, :string, virtual: true
    field :password_confirmation, :string, virtual: true

    timestamps()
  end

  @doc "Changeset for creating new user with a password"
  def changeset_for_create(%User{} = user, attrs) do
    user
    |> cast(attrs, [
      :first_name,
      :last_name,
      :auth_provider,
      :avatar,
      :email,
      :password,
      :password_confirmation,
      :role
      ])
    |> validate_required([
      :first_name,
      :last_name,
      :auth_provider,
      :email,
      :password,
      :password_confirmation,
      :role
      ])
    |> validate_format(:email, ~r/@/)
    |> validate_length(:password, min: 5)
    |> validate_confirmation(:password, message: "Password does not match")
    |> validate_inclusion(:role, ["dossy_creator", "dossy_viewer"])
    |> unique_constraint(:email, message: "Email already taken")
    |> generate_encrypted_password
  end

  # Private -----------------------------

  defp generate_encrypted_password(current_changeset) do
    case current_changeset do
      %Ecto.Changeset{valid?: true, changes: %{password: password}} ->
        put_change(current_changeset, :encrypted_password, Comeonin.Bcrypt.hashpwsalt(password))
      _ ->
        current_changeset
    end
  end
end
defmodule Dossy.Repo.Migrations.AddUserRole do
  use Ecto.Migration

  def change do
    alter table(:accounts_users) do
      add :role, :text
    end
  end
  
  create table(:weather) do
    add :city,    :string, size: 40
    add :temp_lo, :integer
    add :temp_hi, :integer
    add :prcp,    :float

    timestamps()
  end
  
  create index(:posts, [:name])
  drop index(:posts, [:name])
end
mix help
iex -S mix phx.server # like rails c
  h Enum => shows help for Enum
  Dossy.Accounts.__info__(:functions)  => will list functions in this module

mix phx.routes

# DATABASE
mix ecto.gen.migration add_weather_table
mix ecto.migrate
mix ecto.rollback

以上是关于sh Elixir Phoenix Cheatsheet的主要内容,如果未能解决你的问题,请参考以下文章

在 Phoenix / Elixir 中启用跨域资源共享 CORS

Elixir/Phoenix 日期从工作日 + 周数

如何使用 elixir/phoenix 从 csv 文件导入用户?

从 Phoenix / Elixir GET 函数中调用 Typescript 函数

GraphQL Elixir/Phoenix API:Socket 挂起,响应很大

如何安排代码在 Elixir 或 Phoenix 框架中每隔几个小时运行一次?