Sha256: c861f36117466ef29f298e52b4570942a6710f8ba526cd5e40de2b97e240f804

Contents?: true

Size: 1.81 KB

Versions: 1

Compression:

Stored size: 1.81 KB

Contents

require "json"
require "mountapi/response"

module Mountapi
  # The rack application
  # It call the app router to handle request and return json response
  class RackApp
    def initialize(app = nil)
      @app = app
    end

    def call(env)
      Mountapi.call(request(env)).to_rack
    rescue Mountapi::Error::RouteNotFound => e
      if @app
        @app.call(env)
      else
        Mountapi.logger.error(e.to_json_api)
        Mountapi::Response::NotFound.new(e.to_json_api).to_rack
      end
    rescue Mountapi::Error::InvalidResponse => e
      Mountapi.logger.error(e.to_json_api)
      Mountapi::Response::InternalError.new(e.to_json_api).to_rack
    rescue Mountapi::Error::InvalidParameter => e
      Mountapi.logger.error(e.to_json_api)
      Mountapi::Response::BadRequest.new(e.to_json_api).to_rack
    end

    private

    def request(env)
      req = Rack::Request.new(env)
      {
        path: req.path,
        http_method: req.request_method,
        params: params(req),
        options: { base_url: req.base_url, rack_req: req }
      }
    end

    def params(rack_req)
      {
        query: query_params(rack_req),
        body: body_params(rack_req),
        header: header_params(rack_req)
      }
    end

    def body_params(request)
      if request.content_type && request.content_type.split(";").first == "application/json"
        request.body.rewind
        params = request.body.read
        request.body.rewind
        params.empty? ? {} : JSON.parse(params)
      else
        request.params || {}
      end
    end


    def query_params(request)
      request.params
    end

    def header_params(request)
      headers = {}
      request.each_header do |k, v|
        _str, http, name = k.match(/(HTTP_)(.*)/).to_a
        headers[name.split("_").join("-")] = v if http
      end
      headers
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mountapi-0.11.1 lib/mountapi/rack_app.rb