Module: Belt::Helpers::Response
- Included in:
- LambdaHandler, BeltController::Base
- Defined in:
- lib/belt/helpers/response.rb
Instance Method Summary collapse
- #cors_headers(event = nil) ⇒ Object
- #error_response(message, status_code = 400, error_details = nil) ⇒ Object
- #handle_error_and_respond(error, message, context = {}, status_code = 500) ⇒ Object
- #html_response(html, status_code = 200) ⇒ Object
- #success_response(body, status_code = 200) ⇒ Object
Instance Method Details
#cors_headers(event = nil) ⇒ Object
9 10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/belt/helpers/response.rb', line 9 def cors_headers(event = nil) event = @event if event.nil? && instance_variable_defined?(:@event) origin = CorsOrigin.resolve_origin(CorsOrigin.origin_from_event(event)) headers = { 'Access-Control-Allow-Headers' => 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token', 'Access-Control-Allow-Methods' => 'GET,POST,PUT,DELETE,PATCH,OPTIONS', 'Access-Control-Max-Age' => '300', 'Content-Type' => 'application/json' } headers['Access-Control-Allow-Origin'] = origin if origin headers end |
#error_response(message, status_code = 400, error_details = nil) ⇒ Object
26 27 28 29 30 31 32 |
# File 'lib/belt/helpers/response.rb', line 26 def error_response(, status_code = 400, error_details = nil) body = { error: } if error_details body[:details] = error_details.is_a?(Hash) ? error_details : { message: error_details.to_s } end { statusCode: status_code, headers: cors_headers, body: JSON.generate(body) } end |
#handle_error_and_respond(error, message, context = {}, status_code = 500) ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/belt/helpers/response.rb', line 42 def handle_error_and_respond(error, , context = {}, status_code = 500) log_error(, error, context) if verbose_errors_enabled? error_details = { type: error.class.name, message: error., backtrace: ErrorLogging.filter_backtrace(error.backtrace || []), environment: ENV.fetch('ENVIRONMENT', nil) } error_details[:context] = context unless context.empty? error_response(, status_code, error_details) else error_response(, status_code) end end |
#html_response(html, status_code = 200) ⇒ Object
34 35 36 37 38 39 40 |
# File 'lib/belt/helpers/response.rb', line 34 def html_response(html, status_code = 200) event = @event if instance_variable_defined?(:@event) origin = CorsOrigin.resolve_origin(CorsOrigin.origin_from_event(event)) headers = { 'Content-Type' => 'text/html; charset=utf-8' } headers['Access-Control-Allow-Origin'] = origin if origin { statusCode: status_code, headers: headers, body: html } end |
#success_response(body, status_code = 200) ⇒ Object
22 23 24 |
# File 'lib/belt/helpers/response.rb', line 22 def success_response(body, status_code = 200) { statusCode: status_code, headers: cors_headers, body: JSON.generate(body) } end |