Last active
November 9, 2022 13:26
-
-
Save slashdotdash/f1d61b26d6974e65289fa38f9843434e to your computer and use it in GitHub Desktop.
Unique username command dispatch middleware for Commanded
This file contains 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 UniqueUsername do | |
@behaviour Commanded.Middleware | |
alias Commanded.Middleware.Pipeline | |
def before_dispatch(%Pipeline{command: %RegisterUser{} = command} = pipeline) do | |
%RegisterUser{username: username} = command | |
case Repo.insert(%Username{username: username}) do | |
{:ok, _} -> | |
pipeline | |
{:error, %Ecto.Changeset{errors: errors}} -> | |
case Keyword.get(errors, :username) do | |
{"has already been taken", _} -> | |
pipeline | |
|> Pipeline.respond({:error, :username_already_taken}) | |
|> Pipeline.halt() | |
_ -> | |
pipeline | |
|> Pipeline.respond({:error, errors}) | |
|> Pipeline.halt() | |
end | |
end | |
end | |
def before_dispatch(%Pipeline{} = pipeline), do: pipeline | |
def after_dispatch(%Pipeline{} = pipeline), do: pipeline | |
def after_failure(%Pipeline{command: %RegisterUser{} = command} = pipeline) do | |
%RegisterUser{username: username} = command | |
username_query = from(u in Username, where: u.username == ^username) | |
{1, nil} = Repo.delete_all(username_query) | |
pipeline | |
end | |
def after_failure(%Pipeline{} = pipeline), do: pipeline | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment