class WarpEngine::AdminApi::Context
What an operation handler gets: the Operation, the Principal, the coerced params (string keys) and helpers that build a Result.
Attributes
Public Class Methods
# File lib/warp_engine/admin_api/context.rb, line 11 def initialize(operation:, principal:, params:, base_url:, via:) @operation = operation @principal = principal @params = params @base_url = base_url @via = via end
Builds the context; every argument becomes the reader of the same name.
Public Instance Methods
Source
# File lib/warp_engine/admin_api/context.rb, line 20 def [](key) = params[key.to_s]
The param named key.
Source
# File lib/warp_engine/admin_api/context.rb, line 28 def attributes(*keys) names = keys.presence || operation.body&.dig(:properties)&.keys || [] names.map(&:to_s).select { |key| params.key?(key) }.to_h { |key| [ key.underscore, params[key] ] } end
The given params among keys (by default the properties of the operation body) as a hash with snake case keys, ready for assign_attributes.
Source
# File lib/warp_engine/admin_api/context.rb, line 36 def created(data) = Result.new(status: 201, data: data)
A 201 Result with data.
Source
# File lib/warp_engine/admin_api/context.rb, line 24 def id = self[:id]
The id path param.
Source
# File lib/warp_engine/admin_api/context.rb, line 22 def key?(key) = params.key?(key.to_s)
Whether the param key was given.
# File lib/warp_engine/admin_api/context.rb, line 51 def list(scope, serializer = nil, &block) per_page = per_page_value page = [ self[:page].to_i, 1 ].max total = scope.count records = sorted(scope).offset((page - 1) * per_page).limit(per_page).to_a data = block ? records.map(&block) : serializer.render_as_hash(records) pages = (total / per_page.to_f).ceil ok(data, meta: { page: page, perPage: per_page, total: total, totalPages: pages, nextPage: page < pages ? page + 1 : nil }) end
One page of scope as a 200 Result with pagination meta (page, perPage, total, totalPages, nextPage). It honours the page, perPage and sort params; records are rendered with serializer, or with the block when given. Raises a 400 Error for an unknown sort.
Source
# File lib/warp_engine/admin_api/context.rb, line 38 def no_content = Result.new(status: 204)
A 204 Result.
Source
# File lib/warp_engine/admin_api/context.rb, line 34 def ok(data, meta: nil) = Result.new(status: 200, data: data, meta: meta)
A 200 Result with data and an optional meta.
Source
# File lib/warp_engine/admin_api/context.rb, line 41 def save!(record) raise Error.invalid(record) unless record.save record end
Saves record and returns it. Raises Error.invalid (422) when it does not validate.