lib/metatron/controller.rb in metatron-0.5.0 vs lib/metatron/controller.rb in metatron-0.6.0
- old
+ new
@@ -1,38 +1,38 @@
# 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)
+ class Controller
+ class << self
+ def call(env)
+ new(env).call
end
- rescue StandardError => e
- halt(400, { error: "Request must be JSON: #{e.message}}" }.to_json)
end
- error do
- content_type :json
+ attr_accessor :params
- e = env["sinatra.error"]
- resp = { result: "error", message: e.message }
- resp[:trace] = e.full_message if settings.environment.to_s != "production"
- resp.to_json
+ def initialize(env)
+ @env = env
+ @request = Rack::Request.new(env)
end
- def request_body
- @json_body
+ def call
+ begin
+ if request&.content_type&.include?("json")
+ body = request.body.read
+ request.body.rewind if request.body.respond_to?(:rewind)
+
+ self.params = JSON.parse(body) unless body.empty?
+ end
+ rescue JSON::ParserError => e
+ return [400, {}, [{ error: "Request must be JSON: #{e.message}" }.to_json]]
+ end
+
+ _call
end
+
+ private
+
+ attr_reader :request
end
end