Module: Sinja

Defined in:
lib/sinja.rb,
lib/sinja/config.rb,
lib/sinja/errors.rb,
lib/sinja/version.rb,
lib/sinja/resource.rb,
lib/sinja/helpers/nested.rb,
lib/sinja/method_override.rb,
lib/sinja/resource_routes.rb,
lib/sinja/helpers/serializers.rb,
lib/sinja/helpers/relationships.rb,
lib/sinja/relationship_routes/has_one.rb,
lib/sinja/relationship_routes/has_many.rb

Defined Under Namespace

Modules: ConfigUtils, Helpers, RelationshipRoutes, Resource, ResourceRoutes Classes: ActionHelperError, BadRequestError, Config, ConflictError, ForbiddenError, HttpError, MethodNotAllowedError, MethodOverride, NotAcceptableError, NotFoundError, Roles, RolesConfig, SideloadError, SinjaError, UnprocessibleEntityError, UnsupportedTypeError

Constant Summary collapse

DEFER_CODE =
357
MIME_TYPE =
'application/vnd.api+json'
ERROR_CODES =
ObjectSpace.each_object(Class).to_a
.keep_if { |klass| klass < HttpError }
.map! { |c| [(c.const_get(:HTTP_STATUS) rescue nil), c] }
.delete_if { |s, _| s.nil? }
.to_h.freeze
VERSION =
'1.3.0'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object


382
383
384
385
386
387
388
# File 'lib/sinja.rb', line 382

def self.extended(base)
  def base.route(*, **opts)
    opts[:qparams] ||= []

    super
  end
end

.registered(app) ⇒ Object


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/sinja.rb', line 23

def self.registered(app)
  abort "Sinatra::JSONAPI (Sinja) is already registered on #{app}!" \
    if app.respond_to?(:_sinja)

  app.register Sinatra::Namespace

  app.disable :protection, :show_exceptions, :static
  app.set :_sinja, Sinja::Config.new
  app.set :_resource_config, nil # dummy value overridden in each resource

  app.set :actions do |*actions|
    condition do
      actions.each do |action|
        raise ForbiddenError, 'You are not authorized to perform this action' \
          unless can?(action)
        raise MethodNotAllowedError, 'Action or method not implemented or supported' \
          unless respond_to?(action)
      end

      true
    end
  end

  app.set :qcaptures do |*index|
    condition do
      @qcaptures ||= []

      index.to_h.all? do |key, subkeys|
        key = key.to_s

        params[key].is_a?(Hash) && params[key].any? && Array(subkeys).all? do |subkey|
          subkey = subkey.to_s

          # TODO: What if deleting one is successful, but not another?
          # We'll need to restore the hash to its original state.
          @qcaptures << params[key].delete(subkey) if params[key].key?(subkey)
        end.tap do |ok|
          # If us deleting key(s) causes the hash to become empty, delete it.
          params.delete(key) if ok && params[key].empty?
        end
      end
    end
  end

  app.set :qparams do |*allow_params|
    allow_params = allow_params.to_set

    abort "Unexpected query parameter(s) in route definiton" \
      unless allow_params.subset?(settings._sinja.query_params.keys.to_set)

    condition do
      params.each do |key, value|
        key = key.to_sym

        # Ignore interal Sinatra query parameters (e.g. :captures) and any
        # "known" query parameter set to `nil' in the configurable.
        next if !env['rack.request.query_hash'].key?(key.to_s) ||
          settings._sinja.query_params.fetch(key, BasicObject).nil?

        raise BadRequestError, "`#{key}' query parameter not allowed" \
          unless allow_params.include?(key)

        next if env['sinja.normalized'] == params.object_id

        if value.instance_of?(String) && settings._sinja.query_params[key] != String
          params[key.to_s] = value.split(',')
        elsif !value.is_a?(settings._sinja.query_params[key])
          raise BadRequestError, "`#{key}' query parameter malformed"
        end
      end

      return true if env['sinja.normalized'] == params.object_id

      settings._sinja.query_params.each do |key, klass|
        next if klass.nil?

        if respond_to?("normalize_#{key}_params")
          params[key.to_s] = send("normalize_#{key}_params")
        else
          params[key.to_s] ||= klass.new
        end
      end

      # Sinatra re-initializes `params' at namespace boundaries, so we'll
      # reference its object_id in the flag to make sure we only re-normalize
      # the parameters when necessary.
      env['sinja.normalized'] = params.object_id
    end
  end

  app.set(:on) { |block| condition(&block) }

  app.mime_type :api_json, MIME_TYPE

  app.helpers Helpers::Serializers do
    def allow(h={})
      s = Set.new
      h.each do |method, actions|
        s << method if Array(actions).all?(&method(:respond_to?))
      end
      headers 'Allow'=>s.map(&:upcase).join(',')
    end

    def attributes
      dedasherize_names(data.fetch(:attributes, {}))
    end

    if method_defined?(:bad_request?)
      # This screws up our error-handling logic in Sinatra 2.0, so override it.
      # https://github.com/sinatra/sinatra/issues/1211
      # https://github.com/sinatra/sinatra/pull/1212
      def bad_request?
        false
      end
    end

    def can?(action)
      roles = settings._resource_config[:resource].fetch(action, {})[:roles]
      roles.nil? || roles.empty? || roles.intersect?(role)
    end

    def content?
      request.body.respond_to?(:size) && request.body.size > 0 || begin
        request.body.rewind
        request.body.read(1)
      end
    end

    def data
      @data ||= {}
      @data[request.path] ||= begin
        deserialize_request_body.fetch(:data)
      rescue NoMethodError, KeyError
        raise BadRequestError, 'Malformed {json:api} request payload'
      end
    end

    def normalize_filter_params
      return {} unless params[:filter]&.any?

      raise BadRequestError, "Unsupported `filter' query parameter(s)" \
        unless respond_to?(:filter)

      params[:filter].map do |k, v|
        [dedasherize(k).to_sym, v]
      end.to_h
    end

    def filter_by?(action)
      return if params[:filter].empty?

      filter = params[:filter].map { |k, v| [k.to_sym, v] }.to_h
      filter_by = settings.resource_config[action][:filter_by]
      return filter if filter_by.empty? || filter_by.superset?(filter.keys.to_set)

      raise BadRequestError, "Invalid `filter' query parameter(s)"
    end

    def normalize_sort_params
      return {} unless params[:sort]&.any?

      raise BadRequestError, "Unsupported `sort' query parameter(s)" \
        unless respond_to?(:sort)

      params[:sort].map do |k|
        dir = k.sub!(/^-/, '') ? :desc : :asc
        [dedasherize(k).to_sym, dir]
      end.to_h
    end

    def sort_by?(action)
      return if params[:sort].empty?

      sort = params[:sort].map { |k, v| [k.to_sym, v] }.to_h
      sort_by = settings.resource_config[action][:sort_by]
      return sort if sort_by.empty? || sort_by.superset?(sort.keys.to_set)

      raise BadRequestError, "Invalid `sort' query parameter(s)"
    end

    def normalize_page_params
      return {} unless params[:page]&.any?

      raise BadRequestError, "Unsupported `page' query parameter(s)" \
        unless respond_to?(:page)

      params[:page].map do |k, v|
        [dedasherize(k).to_sym, v]
      end.to_h
    end

    def page_using?
      return if params[:page].empty?

      page = params[:page].map { |k, v| [k.to_sym, v] }.to_h
      return page if (page.keys - settings._sinja.page_using.keys).empty?

      raise BadRequestError, "Invalid `page' query parameter(s)"
    end

    def filter_sort_page?(action)
      return enum_for(__callee__, action) unless block_given?

      if filter = filter_by?(action) then yield :filter, filter end
      if sort = sort_by?(action) then yield :sort, sort end
      if page = page_using? then yield :page, page end
    end

    def filter_sort_page(collection, opts)
      collection = filter(collection, opts[:filter]) if opts.key?(:filter)
      collection = sort(collection, opts[:sort]) if opts.key?(:sort)
      collection, pagination = page(collection, opts[:page]) if opts.key?(:page)

      return respond_to?(:finalize) ? finalize(collection) : collection, pagination
    end

    def halt(code, body=nil)
      if exception_class = ERROR_CODES[code]
        raise exception_class, body
      elsif (400...600).include?(code.to_i)
        raise HttpError.new(code.to_i, body)
      else
        super
      end
    end

    def sideloaded?
      env.key?('sinja.passthru')
    end

    def role
      nil
    end

    def role?(*roles)
      Roles[*roles].intersect?(role)
    end

    def sanity_check!(resource_name, id=nil)
      raise ConflictError, 'Resource type in payload does not match endpoint' \
        unless data[:type] && data[:type].to_sym == resource_name

      raise ConflictError, 'Resource ID in payload does not match endpoint' \
        unless id.nil? || data[:id] && data[:id].to_s == id.to_s
    end

    def transaction
      yield
    end
  end

  app.before do
    unless sideloaded?
      raise NotAcceptableError unless request.preferred_type.entry == MIME_TYPE || request.options?
      raise UnsupportedTypeError if content? && (
        request.media_type != MIME_TYPE || request.media_type_params.keys.any? { |k| k != 'charset' }
      )
    end

    content_type :api_json
  end

  app.after do
    body serialize_response_body if response.successful?
  end

  app.not_found do
    serialize_errors
  end

  app.error 400...600 do
    serialize_errors
  end

  app.error StandardError do
    env['sinatra.error'].tap do |e|
      boom =
        if settings._sinja.not_found_exceptions.any?(&e.method(:is_a?))
          NotFoundError.new(e.message) unless e.instance_of?(NotFoundError)
        elsif settings._sinja.conflict_exceptions.any?(&e.method(:is_a?))
          ConflictError.new(e.message) unless e.instance_of?(ConflictError)
        elsif settings._sinja.validation_exceptions.any?(&e.method(:is_a?))
          UnprocessibleEntityError.new(settings._sinja.validation_formatter.(e)) unless e.instance_of?(UnprocessibleEntityError)
        end

      handle_exception!(boom) if boom # re-throw the re-packaged exception
    end

    serialize_errors
  end
end

Instance Method Details

#configure_jsonapi(&block) ⇒ Object


374
375
376
# File 'lib/sinja.rb', line 374

def configure_jsonapi(&block)
  _sinja.configure(&block)
end

#freeze_jsonapiObject


378
379
380
# File 'lib/sinja.rb', line 378

def freeze_jsonapi
  _sinja.freeze
end

#resource(resource_name, konst = nil, **opts, &block) ⇒ Object Also known as: resources


315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'lib/sinja.rb', line 315

def resource(resource_name, konst=nil, **opts, &block)
  abort "Must supply proc constant or block for `resource'" \
    unless block = (konst if konst.instance_of?(Proc)) || block

  warn "DEPRECATED: Pass a block to `resource'; the ability to pass a Proc " \
    'will be removed in a future version of Sinja.' if konst.instance_of?(Proc)

  resource_name = resource_name.to_s
    .pluralize
    .dasherize
    .to_sym

  # trigger default procs
  config = _sinja.resource_config[resource_name]

  # incorporate route options
  config[:route_opts].merge!(opts)

  namespace %r{/#{resource_name}(?![^/])} do
    define_singleton_method(:_resource_config) { config }
    define_singleton_method(:resource_config) { config[:resource] }

    helpers do
      define_method(:sanity_check!) do |*args|
        super(resource_name, *args)
      end
    end

    before %r{/(#{config[:route_opts][:pkre]})(?:/.*)?} do |id|
      self.resource =
        if env.key?('sinja.resource')
          env['sinja.resource']
        elsif respond_to?(:find)
          find(id)
        else
          raise SinjaError, 'Resource locator not defined!'
        end

      raise NotFoundError, "Resource '#{id}' not found" unless resource
    end

    register Resource

    instance_eval(&block)
  end
end

#sinjaObject


364
365
366
367
368
369
370
371
372
# File 'lib/sinja.rb', line 364

def sinja
  if block_given?
    warn "DEPRECATED: Pass a block to `sinja.configure' instead."

    yield _sinja
  else
    _sinja
  end
end