Skip to content

Commit b8f40ed

Browse files
author
Jack Casey
committed
Include more information in RecordNotFound errors.
When supplying a relationship to an existing resource, if the record cannot be found then supply the resource name, id and relative json path in the Graphiti::Errors::NotFound exception raised.
1 parent 4f0b669 commit b8f40ed

File tree

3 files changed

+51
-3
lines changed

3 files changed

+51
-3
lines changed

lib/graphiti/errors.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -722,6 +722,21 @@ def pretty(input)
722722
end
723723

724724
class RecordNotFound < Base
725+
def initialize(resource = nil, id = nil, path = nil)
726+
@resource = resource
727+
@id = id
728+
@path = path
729+
end
730+
731+
def message
732+
if !@resource.nil? && !@id.nil?
733+
"The referenced resource '#{@resource}' with id '#{@id}' could not be found.".tap do |msg|
734+
msg << " Referenced at '#{@path}'" unless @path.nil?
735+
end
736+
else
737+
"Specified Record Not Found"
738+
end
739+
end
725740
end
726741

727742
class RequiredFilter < Base

lib/graphiti/util/persistence.rb

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -177,9 +177,15 @@ def process_has_many(relationships, caller_model)
177177
def process_belongs_to(relationships)
178178
[].tap do |processed|
179179
iterate(only: [:polymorphic_belongs_to, :belongs_to]) do |x|
180-
x[:object] = x[:resource]
181-
.persist_with_relationships(x[:meta], x[:attributes], x[:relationships])
182-
processed << x
180+
begin
181+
id = x.dig(:attributes, :id)
182+
x[:object] = x[:resource]
183+
.persist_with_relationships(x[:meta], x[:attributes], x[:relationships])
184+
processed << x
185+
rescue Graphiti::Errors::RecordNotFound
186+
path = "relationships/#{x.dig(:meta, :jsonapi_type)}"
187+
raise Graphiti::Errors::RecordNotFound.new(x[:sideload].name, id, path)
188+
end
183189
end
184190
end
185191
end

spec/persistence_spec.rb

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2330,6 +2330,33 @@ def self.name
23302330
.to eq(["Description can't be blank"])
23312331
end
23322332
end
2333+
2334+
context "linking to an non-existing related record" do
2335+
let(:payload) do
2336+
{
2337+
data: {
2338+
type: "employees",
2339+
relationships: {
2340+
classification: {
2341+
data: {
2342+
type: "classifications",
2343+
'id': "123"
2344+
}
2345+
}
2346+
}
2347+
}
2348+
}
2349+
end
2350+
2351+
it "responds correctly" do
2352+
employee = klass.build(payload)
2353+
expect { employee.save }.to raise_error(
2354+
Graphiti::Errors::RecordNotFound,
2355+
"The referenced resource 'classification' with id '123' could not be found. " \
2356+
"Referenced at 'relationships/classifications'"
2357+
)
2358+
end
2359+
end
23332360
end
23342361

23352362
describe "has_one" do

0 commit comments

Comments
 (0)