Module: ApiRegulator::ControllerMixin

Defined in:
lib/api_regulator/controller_mixin.rb

Instance Method Summary collapse

Instance Method Details

#api_definitionObject



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/api_regulator/controller_mixin.rb', line 17

def api_definition
  return @api_definition if defined?(@api_definition)

  @api_definition ||= self.class.api_definitions.find do |d|
    d.controller_path == params[:controller] && d.action_name == params[:action]
  end

  raise "API definition not found for #{params[:controller]}##{params[:action]}" unless @api_definition

  @api_definition
end

#api_paramsObject



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
# File 'lib/api_regulator/controller_mixin.rb', line 29

def api_params
  path_params = api_definition.params.select(&:path?).each_with_object({}) do |param, hash|
    hash[param.name.to_sym] = params[param.name] if params.key?(param.name)
  end

  query_params = api_definition.params.select(&:query?).each_with_object({}) do |param, hash|
    hash[param.name.to_sym] = params[param.name] if params.key?(param.name)
  end

  body_params = api_definition.params.select(&:body?)
  permitted_body = body_params.each_with_object({}) do |param, hash|
    case param.type
    when :array
      allowed_params = [build_permitted_keys(param.children)]

      if param.required?
        nested = params.expect(param.name => allowed_params).map { |set| set.to_h }
        hash[param.name.to_sym] = nested
      else
        nested = params.permit(param.name => allowed_params).map { |set| set.to_h }
        hash.merge!(nested)
      end
    when :object
      allowed_params = build_permitted_keys(param.children)

      if param.required?
        nested = params.expect(param.name => allowed_params).to_h
        hash[param.name.to_sym] = nested
      else
        nested = params.permit(param.name => allowed_params).to_h
        hash.merge!(nested)
      end
    else
      hash[param.name.to_sym] = params[param.name]
    end
  end

  path_params.merge(query_params).merge(permitted_body).deep_symbolize_keys
end

#validate_params!Object



3
4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/api_regulator/controller_mixin.rb', line 3

def validate_params!
  check_for_extra_params!

  validator_class = Validator.get(params[:controller], params[:action])

  unless validator_class
    raise "No validator found for HTTP method #{request.method} and API path #{api_definition.path}"
  end
  validator = validator_class.new(api_params)
  unless validator.valid?(params[:action].to_sym)
    raise ApiRegulator::InvalidParams.new(validator.errors)
  end
end