Module: Ant::Server::GrapeDecorator

Defined in:
lib/ant/server/grape.rb

Constant Summary collapse

HTTP_CODES =
{
  success: 200, fail: 400, error: 500, fatal: 500
}.freeze

Class Method Summary collapse

Class Method Details

.configure_handlers(base) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/ant/server/grape.rb', line 24

def self.configure_handlers(base)
  Server::Response.resources(:exceptions).each do |exception_class, level|
    base.rescue_from(exception_class) do |ex|
      response = Ant::Server::GrapeDecorator.handler.call(env, level, ex)
      http_code = Ant::Server::GrapeDecorator.extract_http_code(ex, level)
      error!(response, http_code)
    end
  end
  base.rescue_from(Grape::Exceptions::Base) do |ex|
    ant_ex = Ant::Exceptions::AntFail.new(ex.message)
    response = Ant::Server::GrapeDecorator
               .handler.call(env, :fail, ant_ex)
    error!(response, 400)
  end
  base.rescue_from(:all) do |ex|
    level = :fatal
    response = Ant::Server::GrapeDecorator.handler.call(env, level, ex)
    http_code = Ant::Server::GrapeDecorator.extract_http_code(ex, level)
    error!(response, http_code)
  end
end

.configure_logger(base) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
# File 'lib/ant/server/grape.rb', line 56

def self.configure_logger(base)
  base.before do
    params[:__init_time] = Time.now
  end
  base.after do
    params = env['api.endpoint'].params
    request = env['api.endpoint'].request
    pkg = RequestResponse.new(request: request, params: params)
    Server::Response.logger.access(pkg)
  end
end

.extract_http_code(exception, level) ⇒ Object



19
20
21
22
# File 'lib/ant/server/grape.rb', line 19

def self.extract_http_code(exception, level)
  default = HTTP_CODES[level] || 500
  exception.respond_to?(:http_code) ? exception.http_code : default
end

.handlerObject



4
5
6
7
8
9
10
11
12
13
# File 'lib/ant/server/grape.rb', line 4

def self.handler
  lambda do |env, level, ex|
    params = env['api.endpoint'].params
    request = env['api.endpoint'].request
    pkg = RequestResponse.new(request: request, params: params)
    pkg.exception = ex
    Server::Response.logger.send(level, pkg)
    Server::Response.format.send(level, pkg)
  end
end

.included(base) ⇒ Object



46
47
48
49
50
51
52
53
54
# File 'lib/ant/server/grape.rb', line 46

def self.included(base)
  base.formatter(:json, lambda do |response, _|
    pkg = RequestResponse.new(request: {}, params: {})
    pkg.result = response
    Server::Response.format.send(:success, pkg).to_json
  end)
  configure_logger(base)
  configure_handlers(base)
end