Module: Snapi::SinatraExtensionHelper

Defined in:
lib/snapi/sinatra_extension_helper.rb

Instance Method Summary collapse

Instance Method Details

#response_wrapper(data = {}, response_code = 200, errors = []) ⇒ Object

Helper that handles wrapping all API data requests in a standard format that includes status and error messages (if there were any).

Parameters:

  • data (Hash) (defaults to: {})

    Singular or multiple data objects the client requested, should include a JSON schema attribute to allow for response validation.

  • response_code (Fixnum) (defaults to: 200)

    HTTP Status code to return

  • errors (Array<String>) (defaults to: [])

    List of errors that occured while processing the request.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/snapi/sinatra_extension_helper.rb', line 14

def response_wrapper(data = {}, response_code = 200, errors = [])
  time_taken = nil

  if block_given?
    time_start = Time.now

    begin
      data = data.deep_merge(yield)
    rescue Exception => e
      response_code = 500
      errors << "#{e.class.name}: #{e.backtrace}"
    end

    time_end = Time.now
    time_taken = (time_end - time_start)
  end

  response = { status: response_code, data: data }
  response[:errors] = errors unless errors.empty?
  response[:execution_time] = time_taken unless time_taken.nil?

  # Use halt to prevent all further processing
  halt(response_code, response.to_json)
end