Class: OpenapiFirst::ErrorResponses::Jsonapi

Inherits:
Object
  • Object
show all
Includes:
OpenapiFirst::ErrorResponse
Defined in:
lib/openapi_first/error_responses/jsonapi.rb

Overview

A JSON:API conform error response. See jsonapi.org/.

Instance Attribute Summary

Attributes included from OpenapiFirst::ErrorResponse

#failure

Instance Method Summary collapse

Methods included from OpenapiFirst::ErrorResponse

#initialize, #render, #status

Instance Method Details

#bodyObject



10
11
12
# File 'lib/openapi_first/error_responses/jsonapi.rb', line 10

def body
  MultiJson.dump({ errors: serialized_errors })
end

#content_typeObject



14
15
16
# File 'lib/openapi_first/error_responses/jsonapi.rb', line 14

def content_type
  'application/vnd.api+json'
end

#default_errorsObject



32
33
34
35
36
37
# File 'lib/openapi_first/error_responses/jsonapi.rb', line 32

def default_errors
  [{
    status: status.to_s,
    title: Rack::Utils::HTTP_STATUS_CODES[status]
  }]
end

#pointer(data_pointer) ⇒ Object



52
53
54
55
56
# File 'lib/openapi_first/error_responses/jsonapi.rb', line 52

def pointer(data_pointer)
  return data_pointer if failure.type == :invalid_body

  data_pointer.delete_prefix('/')
end

#pointer_keyObject



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/openapi_first/error_responses/jsonapi.rb', line 39

def pointer_key
  case failure.type
  when :invalid_body
    :pointer
  when :invalid_query, :invalid_path
    :parameter
  when :invalid_header
    :header
  when :invalid_cookie
    :cookie
  end
end

#serialized_errorsObject



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/openapi_first/error_responses/jsonapi.rb', line 18

def serialized_errors
  return default_errors unless failure.errors

  key = pointer_key
  failure.errors.map do |error|
    {
      status: status.to_s,
      source: { key => pointer(error.data_pointer) },
      title: error.message,
      code: error.type
    }
  end
end