Skip to content

Commit

Permalink
improve create function to be more resilient to race condition
Browse files Browse the repository at this point in the history
Signed-off-by: Zack Siri <[email protected]>
  • Loading branch information
zacksiri committed Nov 9, 2023
1 parent 268dee8 commit 5af4c8c
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions lib/uplink/packages/app/manager.ex
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,32 @@ defmodule Uplink.Packages.App.Manager do
|> Repo.get_by(slug: slug)
|> case do
nil ->
%App{}
|> App.changeset(%{slug: slug})
|> Repo.insert!()
create(%{slug: slug})

%App{} = app ->
app
end
end

def create(params) do
%App{}
|> App.changeset(params)
|> Repo.insert()
|> case do
{:ok, app} ->
app

{:error,
%Ecto.Changeset{
changes: %{slug: slug},
errors: [
slug: {_, [constraint: :unique, constraint_name: "apps_slug_index"]}
]
}} ->
Repo.get_by!(App, slug: slug)

error ->
error
end
end
end

0 comments on commit 5af4c8c

Please sign in to comment.