Last active
April 9, 2018 21:54
-
-
Save zorbash/2ce7b183bca529f5b84ed48ed27cb29f 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 Document.UpdatePipeline do | |
use Opus.Pipeline | |
check :validate_params, with: &match(%{"id" => id} when is_number(id), &1.params) | |
step :fetch_document, with: &(put_in &1[:document], Document.get(get_in(&1, [:params, "id"])), error_message: :not_found | |
check :can_view?, with: &Authorizer.can_view(&1.document, &1.user) | |
check :can_edit?, with: &Authorizer.can_view(&1.document, &1.user) | |
step :update, with: &(put_in &1[:updated_document], Documents.update(&1.document, &1.params)) | |
tee :notify, with: &Notifications.push_document_updated(&1.updated_document) | |
step :finalize, with: &(&1.updated_document) | |
end | |
# Controller Code | |
def update(conn, params \\ %{}) do | |
case Document.UpdatePipeline.call(%{user: conn.assigns.user, params: params}) do | |
{:ok, document} -> json(conn, document) | |
{:error, %{error: error, stage: stage}} when error == :not_found or stage: :can_view? -> | |
render(conn, ErrorView, :"404") | |
{:error, %{stage: :can_edit?}} -> | |
render(conn, ErrorView, :"403") | |
{:error, %{error: %Ecto.Changeset{} = changeset}} | |
render(conn, ErrorView, :"400", changeset) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment