Created
October 17, 2016 21:52
-
-
Save lasseebert/a8be55089faaa69c2eb4dac3c36c099f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| defmodule MyApp.UserController do | |
| use MyApp.Web, :controller | |
| def create(conn, params) do | |
| attrs = %{email: params["email"]} | |
| case MyApp.Users.Invite.call(attrs) do | |
| {:ok, user} -> | |
| render_user(conn, user) | |
| {:error, :invalid_email} -> | |
| resp(conn, 400, %{message: "email is invalid"} |> Poison.encode!) | |
| end | |
| end | |
| defp render_user(conn, user) do | |
| {:ok, body} = %{ | |
| id: user.id, | |
| email: user.email | |
| } | |
| |> Poison.encode | |
| conn | |
| |> resp(201, body) | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| defmodule MyApp.Users.Invite do | |
| alias MyApp.User | |
| alias MyApp.Repo | |
| @create_params [:email] | |
| def call(%{email: email}) do | |
| with :ok <- validate_email(email) do | |
| |> build_changeset | |
| |> create_user | |
| end | |
| end | |
| defp build_changeset(email) do | |
| params = %{email: email} | |
| %User{} | |
| |> Ecto.Changeset.cast(params, @create_params) | |
| |> Ecto.Changeset.unique_constraint(:email) | |
| end | |
| defp create_user(changeset) do | |
| changeset | |
| |> Repo.insert | |
| end | |
| defp validate_email(email) do | |
| case String.match?(email, ~r/@/) do | |
| true -> :ok | |
| false -> {:error, :invalid_email} | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment