Skip to content

Commit 077b64a

Browse files
committed
Create method "JSONAPI::Utils#jsonapi_format_errors"
1 parent 5d82922 commit 077b64a

File tree

2 files changed

+18
-17
lines changed

2 files changed

+18
-17
lines changed

lib/jsonapi/utils/response/formatters.rb

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,19 @@ def jsonapi_format(records, options = {})
1313

1414
alias_method :jsonapi_serialize, :jsonapi_format
1515

16-
module_function
16+
def jsonapi_format_errors(data)
17+
data = JSONAPI::Utils::Exceptions::ActiveRecord.new(data) if data.is_a?(ActiveRecord::Base)
18+
errors = data.respond_to?(:errors) ? data.errors : data
19+
JSONAPI::Utils::Support::Error.sanitize(errors)
20+
end
21+
22+
protected
23+
24+
def correct_media_type
25+
if response.body.size > 0
26+
response.headers['Content-Type'] = JSONAPI::MEDIA_TYPE
27+
end
28+
end
1729

1830
def build_response_document(records, options)
1931
results = JSONAPI::OperationResults.new

lib/jsonapi/utils/response/renders.rb

Lines changed: 5 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -8,26 +8,15 @@ def jsonapi_render(json:, status: nil, options: {})
88
rescue => e
99
handle_exceptions(e)
1010
ensure
11-
if response.body.size > 0
12-
response.headers['Content-Type'] = JSONAPI::MEDIA_TYPE
13-
end
11+
correct_media_type
1412
end
1513

1614
def jsonapi_render_errors(exception = nil, json: nil, status: nil)
17-
unless exception.nil?
18-
json = JSONAPI::ErrorsOperationResult.new(exception.errors[0].code, exception.errors)
19-
end
20-
21-
json = JSONAPI::Utils::Exceptions::ActiveRecord.new(json) if json.is_a?(ActiveRecord::Base)
22-
json = json.errors if json.respond_to?(:errors)
23-
errors = JSONAPI::Utils::Support::Error.sanitize(json)
24-
status = status || errors.try(:first).try(:[], :status)
25-
26-
render json: { errors: errors }, status: status
15+
body = jsonapi_format_errors(exception || json)
16+
status = status || body.try(:first).try(:[], :status)
17+
render json: { errors: body }, status: status
2718
ensure
28-
if response.body.size > 0
29-
response.headers['Content-Type'] = JSONAPI::MEDIA_TYPE
30-
end
19+
correct_media_type
3120
end
3221

3322
def jsonapi_render_internal_server_error

0 commit comments

Comments
 (0)