Module: Sinja::Helpers::Serializers

Defined in:
lib/sinja/helpers/serializers.rb

Constant Summary collapse

VALID_PAGINATION_KEYS =
Set.new(%i[self first prev next last]).freeze

Instance Method Summary collapse

Instance Method Details

#dedasherize(s = nil) ⇒ Object


13
14
15
# File 'lib/sinja/helpers/serializers.rb', line 13

def dedasherize(s=nil)
  s.to_s.underscore.send(s.instance_of?(Symbol) ? :to_sym : :itself)
end

#dedasherize_names(*args) ⇒ Object


17
18
19
# File 'lib/sinja/helpers/serializers.rb', line 17

def dedasherize_names(*args)
  _dedasherize_names(*args).to_h
end

#deserialize_request_bodyObject


29
30
31
32
33
34
35
36
# File 'lib/sinja/helpers/serializers.rb', line 29

def deserialize_request_body
  return {} unless content?

  request.body.rewind
  JSON.parse(request.body.read, :symbolize_names=>true)
rescue JSON::ParserError
  raise BadRequestError, 'Malformed JSON in the request body'
end

#error_hash(title: nil, detail: nil, source: nil) ⇒ Object


198
199
200
201
202
203
204
205
206
207
# File 'lib/sinja/helpers/serializers.rb', line 198

def error_hash(title: nil, detail: nil, source: nil)
  [
    { :id=>SecureRandom.uuid }.tap do |hash|
      hash[:title] = title if title
      hash[:detail] = detail if detail
      hash[:status] = status.to_s if status
      hash[:source] = source if source
    end
  ]
end

#exception_title(e) ⇒ Object


209
210
211
# File 'lib/sinja/helpers/serializers.rb', line 209

def exception_title(e)
  e.respond_to?(:title) ? e.title : e.class.name.demodulize.titleize
end

#include_exclude!(options) ⇒ Object


49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/sinja/helpers/serializers.rb', line 49

def include_exclude!(options)
  included, default, excluded =
    params[:include],
    options.delete(:include) || [],
    options.delete(:exclude) || []

  if included.empty?
    included = default.is_a?(Array) ? default : default.split(',')

    return included if included.empty?
  end

  excluded = excluded.is_a?(Array) ? excluded : excluded.split(',')
  unless excluded.empty?
    excluded = Set.new(excluded)
    included.delete_if do |termstr|
      terms = termstr.split('.')
      terms.length.times.any? do |i|
        excluded.include?(terms.take(i.succ).join('.'))
      end
    end

    return included if included.empty?
  end

  return included unless settings._resource_config

  # Walk the tree and try to exclude based on fetch and pluck permissions
  included.keep_if do |termstr|
    catch :keep? do
      *terms, last_term = termstr.split('.')

      # Start cursor at root of current resource
      config = settings._resource_config
      terms.each do |term|
        # Move cursor through each term, avoiding the default proc,
        # halting if no roles found, i.e. client asked to include
        # something that Sinja doesn't know about
        throw :keep?, true unless config =
          settings._sinja.resource_config.fetch(term.pluralize.to_sym, nil)
      end

      throw :keep?, true unless roles =
        config.dig(:has_many, last_term.pluralize.to_sym, :fetch, :roles) ||
        config.dig(:has_one, last_term.singularize.to_sym, :pluck, :roles)

      throw :keep?, roles && (roles.empty? || roles.intersect?(role))
    end
  end
end

#serialize_errorsObject


213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/sinja/helpers/serializers.rb', line 213

def serialize_errors
  raise env['sinatra.error'] if env['sinatra.error'] && sideloaded?

  abody = Array(body)
  error_hashes =
    if abody.all? { |error| error.is_a?(Hash) }
      # `halt' with a hash or array of hashes
      abody.flat_map(&method(:error_hash))
    elsif not_found?
      # `not_found' or `halt 404'
      message = abody.first.to_s
      error_hash \
        :title=>'Not Found Error',
        :detail=>(message unless message == '<h1>Not Found</h1>')
    elsif abody.all? { |error| error.is_a?(String) }
      # Try to repackage a JSON-encoded middleware error
      begin
        abody.flat_map do |error|
          miderr = JSON.parse(error, :symbolize_names=>true)
          error_hash \
            :title=>'Middleware Error',
            :detail=>(miderr.key?(:error) ? miderr[:error] : error)
        end
      rescue JSON::ParserError
        abody.flat_map do |error|
          error_hash \
            :title=>'Middleware Error',
            :detail=>error
        end
      end
    else
      # `halt'
      error_hash \
        :title=>'Unknown Error(s)',
        :detail=>abody.to_s
    end unless abody.empty?

  # Exception already contains formatted errors
  error_hashes ||= env['sinatra.error'].error_hashes \
    if env['sinatra.error'].respond_to?(:error_hashes)

  error_hashes ||=
    case e = env['sinatra.error']
    when UnprocessibleEntityError
      e.tuples.flat_map do |key, full_message, type=:attributes|
        error_hash \
          :title=>exception_title(e),
          :detail=>full_message.to_s,
          :source=>{
            :pointer=>(key ? "/data/#{type}/#{key.to_s.dasherize}" : '/data')
          }
      end
    when Exception
      error_hash \
        :title=>exception_title(e),
        :detail=>(e.message.to_s unless e.message == e.class.name)
    else
      error_hash \
        :title=>'Unknown Error'
    end

  if block = settings._sinja.error_logger
    error_hashes.each { |h| instance_exec(h, &block) }
  end

  content_type :api_json
  JSON.send settings._sinja.json_error_generator,
    ::JSONAPI::Serializer.serialize_errors(error_hashes)
end

#serialize_linkage(model, rel, options = {}) ⇒ Object


174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/sinja/helpers/serializers.rb', line 174

def serialize_linkage(model, rel, options={})
  options[:is_collection] = false
  options = settings._sinja.serializer_opts.merge(options)

  options[:serializer] ||= ::JSONAPI::Serializer.find_serializer_class(model, options)
  options[:include] = options[:serializer].new(model, options).format_name(rel)

  # TODO: This is extremely wasteful. Refactor JAS to expose the linkage serializer?
  content = ::JSONAPI::Serializer.serialize(model, options)
  content['data']['relationships'].fetch(options[:include]).tap do |linkage|
    %w[meta jsonapi].each do |key|
      linkage[key] = content[key] if content.key?(key)
    end
  end
end

#serialize_linkage?(updated = false, options = {}) ⇒ Boolean

Returns:

  • (Boolean)

190
191
192
# File 'lib/sinja/helpers/serializers.rb', line 190

def serialize_linkage?(updated=false, options={})
  body updated ? serialize_linkage(options) : serialize_model?(nil, options)
end

#serialize_linkages?(updated = false, options = {}) ⇒ Boolean

Returns:

  • (Boolean)

194
195
196
# File 'lib/sinja/helpers/serializers.rb', line 194

def serialize_linkages?(updated=false, options={})
  body updated ? serialize_linkage(options) : serialize_models?([], options)
end

#serialize_model(model = nil, options = {}) ⇒ Object


100
101
102
103
104
105
106
107
108
109
# File 'lib/sinja/helpers/serializers.rb', line 100

def serialize_model(model=nil, options={})
  options[:is_collection] = false
  options[:include] = include_exclude!(options)
  options[:fields] ||= params[:fields] unless params[:fields].empty?
  options = settings._sinja.serializer_opts.merge(options)

  ::JSONAPI::Serializer.serialize(model, options)
rescue ::JSONAPI::Serializer::InvalidIncludeError=>e
  raise BadRequestError, e
end

#serialize_model?(model = nil, options = {}) ⇒ Boolean

Returns:

  • (Boolean)

111
112
113
114
115
116
117
118
119
# File 'lib/sinja/helpers/serializers.rb', line 111

def serialize_model?(model=nil, options={})
  if model
    body serialize_model(model, options)
  elsif options.key?(:meta)
    body serialize_model(nil, :meta=>options[:meta])
  else
    status 204
  end
end

#serialize_models(models = [], options = {}, pagination = nil) ⇒ Object


121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/sinja/helpers/serializers.rb', line 121

def serialize_models(models=[], options={}, pagination=nil)
  options[:is_collection] = true
  options[:include] = include_exclude!(options)
  options[:fields] ||= params[:fields] unless params[:fields].empty?
  options = settings._sinja.serializer_opts.merge(options)

  if pagination
    # Whitelist pagination keys and dasherize query parameter names
    pagination = VALID_PAGINATION_KEYS
      .select(&pagination.method(:key?))
      .map! do |outer_key|
        [outer_key, pagination[outer_key].map do |inner_key, value|
          [inner_key.to_s.dasherize.to_sym, value]
        end.to_h]
      end.to_h

    options[:meta] ||= {}
    options[:meta][:pagination] = pagination

    options[:links] ||= {}
    options[:links][:self] = request.url unless pagination.key?(:self)

    base_query = Rack::Utils.build_nested_query \
      env['rack.request.query_hash'].dup.tap { |h| h.delete('page') }

    self_link, join_char =
      if base_query.empty?
        [request.path, ??]
      else
        ["#{request.path}?#{base_query}", ?&]
      end

    options[:links].merge!(pagination.map do |key, value|
      [key, [self_link,
        Rack::Utils.build_nested_query(:page=>value)].join(join_char)]
    end.to_h)
  end

  ::JSONAPI::Serializer.serialize(Array(models), options)
rescue ::JSONAPI::Serializer::InvalidIncludeError=>e
  raise BadRequestError, e
end

#serialize_models?(models = [], options = {}, pagination = nil) ⇒ Boolean

Returns:

  • (Boolean)

164
165
166
167
168
169
170
171
172
# File 'lib/sinja/helpers/serializers.rb', line 164

def serialize_models?(models=[], options={}, pagination=nil)
  if Array(models).any?
    body serialize_models(models, options, pagination)
  elsif options.key?(:meta)
    body serialize_models([], :meta=>options[:meta])
  else
    status 204
  end
end

#serialize_response_bodyObject


38
39
40
41
42
43
44
45
46
47
# File 'lib/sinja/helpers/serializers.rb', line 38

def serialize_response_body
  case response.content_type[/^[^;]+/]
  when /json$/, /javascript$/
    JSON.send(settings._sinja.json_generator, response.body)
  else
    Array(response.body).map!(&:to_s)
  end
rescue JSON::GeneratorError
  raise BadRequestError, 'Unserializable entities in the response body'
end