Class: Uc3DmpApiCore::Responder

Inherits:
Object
  • Object
show all
Defined in:
lib/uc3-dmp-api-core/responder.rb

Overview

Use Rails’ ActiveResource to communicate with the DMPHub REST API

Constant Summary collapse

DEFAULT_PAGE =
1
DEFAULT_PER_PAGE =
25
MAXIMUM_PER_PAGE =
250
DEFAULT_STATUS_CODE =
500
TIMESTAMP_FORMAT =
'%Y-%m-%dT%H:%M:%S%L%Z'
MSG_INVALID_ARGS =
'Invalid arguments'

Class Method Summary collapse

Class Method Details

.respond(status: DEFAULT_STATUS_CODE, logger: nil, items: [], errors: [], **args) ⇒ Object

Standardized Lambda response

Expects the following inputs:

- status:       an HTTP status code (defaults to DEFAULT_STATUS_CODE)
- items:        an array of Hashes
- errors:       and array of Strings
- args:         currently only allows for the Lambda :event

Returns a hash that is a valid Lambda API response


rubocop:disable Metrics/AbcSize



28
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
# File 'lib/uc3-dmp-api-core/responder.rb', line 28

def respond(status: DEFAULT_STATUS_CODE, logger: nil, items: [], errors: [], **args)
  url = _url_from_event(event: args[:event]) || SsmReader.get_ssm_value(key: 'api_base_url')
  return _standard_error(url: url) if url.nil?

  args = JSON.parse(args.to_json)
  errors = [errors] unless errors.nil? || errors.is_a?(Array)
  item_count = items.is_a?(Array) ? items.length : 0

  body = {
    status: status.to_i,
    requested: url,
    requested_at: Time.now.strftime(TIMESTAMP_FORMAT),
    total_items: item_count,
    items: items.is_a?(Array) ? Paginator.paginate(params: args, results: items) : [],
    errors: errors
  }
  body = body.merge(Paginator.pagination_meta(url: url, item_count: item_count, params: args))

  # If this is a server error, then notify the administrator!
  if status.to_s[0] == '5' && !logger.nil?
    logger.error(message: errors, details: body)
    Notifier.notify_administrator(source: logger.source, details: body, event: logger.event)
  end

  { statusCode: status.to_i, body: body.compact.to_json, headers: headers }
rescue StandardError => e
  puts "Uc3DmpApiCore.Responder.respond - #{e.message}"
  puts " - STACK: #{e.backtrace}"
  _standard_error(url: url)
end