Sha256: 9f8d001b5fa6d14273e4a15bfbb2fef2dd7e9e192f7024c0cf88f38bb9030af9

Contents?: true

Size: 977 Bytes

Versions: 2

Compression:

Stored size: 977 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

2 entries across 2 versions & 1 rubygems

Version Path
metatron-0.5.0 lib/metatron/controller.rb
metatron-0.4.2 lib/metatron/controller.rb