Skip to content

Commit b379967

Browse files
committed
fix: handle race conditions when creating a pacticipant
1 parent f6cfb19 commit b379967

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

lib/pact_broker/pacticipants/repository.rb

+7-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,13 @@ def find_by_name_or_create name
4242
end
4343

4444
def create args
45-
PactBroker::Domain::Pacticipant.new(name: args[:name], repository_url: args[:repository_url]).save(raise_on_save_failure: true)
45+
id = PactBroker::Domain::Pacticipant.dataset.insert_ignore.insert(
46+
name: args[:name],
47+
repository_url: args[:repository_url],
48+
created_at: Sequel.datetime_class.now,
49+
updated_at: Sequel.datetime_class.now
50+
)
51+
PactBroker::Domain::Pacticipant.find(id: id)
4652
end
4753

4854
def pacticipant_names

spec/lib/pact_broker/pacticipants/repository_spec.rb

+33
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,39 @@
55
module PactBroker
66
module Pacticipants
77
describe Repository do
8+
describe "#create" do
9+
let(:repository) { Repository.new }
10+
11+
subject { repository.create(name: "Foo") }
12+
13+
context "when the pacticipant does not already exist" do
14+
before do
15+
TestDataBuilder.new.create_pacticipant("Bar")
16+
end
17+
18+
subject { repository.create(name: "Foo") }
19+
20+
it "returns the new pacticipant" do
21+
expect(subject).to be_a(PactBroker::Domain::Pacticipant)
22+
expect(subject.name).to eq "Foo"
23+
end
24+
end
25+
26+
context "when a race condition occurs and the pacticipant was already created by another request" do
27+
before do
28+
TestDataBuilder.new.create_pacticipant("Foo")
29+
end
30+
31+
it "does not raise an error" do
32+
subject
33+
end
34+
35+
it "returns the existing pacticipant" do
36+
expect(subject).to be_a(PactBroker::Domain::Pacticipant)
37+
expect(subject.name).to eq "Foo"
38+
end
39+
end
40+
end
841

942
describe "#find" do
1043
before do

0 commit comments

Comments
 (0)