From 9a0004ba70c24b9f6a3fc6cf74e9898f90c8abd9 Mon Sep 17 00:00:00 2001 From: Jeremy Johnstone Date: Sun, 9 Sep 2018 19:44:03 -0400 Subject: [PATCH 1/2] 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. --- lib/jsonapi_compliable/deserializer.rb | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/lib/jsonapi_compliable/deserializer.rb b/lib/jsonapi_compliable/deserializer.rb index 39d3945..3fb7e52 100644 --- a/lib/jsonapi_compliable/deserializer.rb +++ b/lib/jsonapi_compliable/deserializer.rb @@ -48,14 +48,23 @@ class JsonapiCompliable::Deserializer # @param payload [Hash] The incoming payload with symbolized keys # @param env [Hash] the Rack env (e.g. +request.env+). def initialize(payload, env) - @payload = payload + @payload = payload || {} @payload = @payload[:_jsonapi] if @payload.has_key?(:_jsonapi) @env = env + validate_content_type + end + + # checks Content-Type header and prints a warning if it doesn't seem correct + def validate_content_type + content_type = @env['CONTENT_TYPE'] || "" + if !(content_type.include?("application/json") || content_type.include?("application/vnd.api+json")) + print("WARNING - JSONAPI Compliable :: Content-Type header appears to be set to an invalid value: #{content_type}\n") + end end # @return [Hash] the raw :data value of the payload def data - @payload[:data] + @payload[:data] || {} end # @return [String] the raw :id value of the payload From 6107483f839306ab35cc2768a3af017cdb346020 Mon Sep 17 00:00:00 2001 From: Jeremy Johnstone Date: Sun, 9 Sep 2018 20:03:34 -0400 Subject: [PATCH 2/2] Make force_includes? handle nil or empty both --- lib/jsonapi_compliable/base.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/jsonapi_compliable/base.rb b/lib/jsonapi_compliable/base.rb index 4107381..55d380b 100644 --- a/lib/jsonapi_compliable/base.rb +++ b/lib/jsonapi_compliable/base.rb @@ -345,7 +345,7 @@ def _persist end def force_includes? - not deserialized_params.data.nil? + not (deserialized_params.data.nil? || deserialized_params.data.empty?) end def perform_render_jsonapi(opts)