Sha256: 4d8ce66c6c60bd728967e3b290d2a51c71624620e6de3c27d0e9d8748439a19a

Contents?: true

Size: 978 Bytes

Versions: 26

Compression:

Stored size: 978 Bytes

Contents

# frozen_string_literal: true

module Metatron
  # Base class for API services
  class Controller < Sinatra::Base
    helpers Sinatra::CustomLogger

    configure do
      set :protection, except: :http_origin
      set :logging, true
      set :logger, Metatron::LOGGER
      set :show_exceptions, false
    end

    before do
      # Sets up a useful variable (@json_body) for accessing a parsed request body
      if request.content_type&.include?("json") && !request.body.read.empty?
        request.body.rewind
        @json_body = JSON.parse(request.body.read)
      end
    rescue StandardError => e
      halt(400, { error: "Request must be JSON: #{e.message}}" }.to_json)
    end

    error do
      content_type :json

      e = env["sinatra.error"]
      resp = { result: "error", message: e.message }
      resp[:trace] = e.full_message if settings.environment.to_s != "production"
      resp.to_json
    end

    def request_body
      @json_body
    end
  end
end

Version data entries

26 entries across 26 versions & 1 rubygems

Version Path
metatron-0.1.5 lib/metatron/controller.rb
metatron-0.1.4 lib/metatron/controller.rb
metatron-0.1.3 lib/metatron/controller.rb
metatron-0.1.2 lib/metatron/controller.rb
metatron-0.1.1 lib/metatron/controller.rb
metatron-0.1.0 lib/metatron/controller.rb