Skip to content

Instantly share code, notes, and snippets.

@slashdotdash
Last active November 9, 2022 13:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slashdotdash/f1d61b26d6974e65289fa38f9843434e to your computer and use it in GitHub Desktop.
Save slashdotdash/f1d61b26d6974e65289fa38f9843434e to your computer and use it in GitHub Desktop.
Unique username command dispatch middleware for Commanded
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