# frozen_string_literal: true require "mountapi/response/ok" module Mountapi module Handler # The mixin to include in your handler class # # You have to define a call instance method that may re-arrange parameters # and call you application service. # # Given the result of the application service call you choose the response that fit # # The call method has access to the `params` instance attribute reader. # It contains the hash with the request parameters # # The `options` variable is also accessible in order to inject dependency for test # And for later compatibility module Behaviour def self.included(base) base.class_eval do extend ClassMethods include InstanceMethods attr_reader :params, :options def initialize(params, options = {}) @params = params @options = options end end end # extend instance module InstanceMethods def base_url options[:base_url] end def url_for(operation_id, options = {}) Mountapi.url_for(operation_id, base_url, options) end def ok(*args) Mountapi::Response::Ok.new(*args) end def not_found(*args) Mountapi::Response::NotFound.new(*args) end def bad_request(*args) Mountapi::Response::BadRequest.new(*args) end def internal_error(*args) Mountapi::Response::InternalError.new(*args) end def forbidden(*args) Mountapi::Response::Forbidden.new(*args) end def call raise NotImplementedError end def response @response ||= Rack::Response.new([]) end def role_allowed? if Mountapi.config.user_info_adapter && self.class.roles Mountapi.config.user_info_adapter.call(params, self.class.roles) else true end end end # extend class module ClassMethods def call(params, options = {}) instance = new(params, options) instance.role_allowed? ? instance.call : instance.forbidden("Not Allowed") end def operation_id(*ids) ids.each { |id| Mountapi.handlers.register(id, self) } end def allowed_roles(*roles) @roles = roles end attr_reader :roles end end end end