Skip to content

Commit c142f24

Browse files
jsjohnstrichmolj
authored andcommitted
Improve error handling in JSONAPI deserializer (#139)
* Improve error handling in JSONAPI deserializer 1) Add conditional checks for `@payload` and `data` to not return nils 2) Print a warning when Content-Type header is set to something other than what JSONAPI expects to lead the developer in the right direction to fix the issue. * Make force_includes? handle nil or empty both
1 parent 8a5a8c4 commit c142f24

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

lib/jsonapi_compliable/base.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -345,7 +345,7 @@ def _persist
345345
end
346346

347347
def force_includes?
348-
not deserialized_params.data.nil?
348+
not (deserialized_params.data.nil? || deserialized_params.data.empty?)
349349
end
350350

351351
def perform_render_jsonapi(opts)

lib/jsonapi_compliable/deserializer.rb

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,14 +48,23 @@ class JsonapiCompliable::Deserializer
4848
# @param payload [Hash] The incoming payload with symbolized keys
4949
# @param env [Hash] the Rack env (e.g. +request.env+).
5050
def initialize(payload, env)
51-
@payload = payload
51+
@payload = payload || {}
5252
@payload = @payload[:_jsonapi] if @payload.has_key?(:_jsonapi)
5353
@env = env
54+
validate_content_type
55+
end
56+
57+
# checks Content-Type header and prints a warning if it doesn't seem correct
58+
def validate_content_type
59+
content_type = @env['CONTENT_TYPE'] || ""
60+
if !(content_type.include?("application/json") || content_type.include?("application/vnd.api+json"))
61+
print("WARNING - JSONAPI Compliable :: Content-Type header appears to be set to an invalid value: #{content_type}\n")
62+
end
5463
end
5564

5665
# @return [Hash] the raw :data value of the payload
5766
def data
58-
@payload[:data]
67+
@payload[:data] || {}
5968
end
6069

6170
# @return [String] the raw :id value of the payload

0 commit comments

Comments
 (0)