Class: AutonomaRails::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/autonoma_rails/server.rb

Overview

Rack middleware alternative for mounting Autonoma as a Rack app.

Instance Method Summary collapse

Constructor Details

#initialize(app, config, path: "/api/autonoma") ⇒ Middleware

Returns a new instance of Middleware.



52
53
54
55
56
# File 'lib/autonoma_rails/server.rb', line 52

def initialize(app, config, path: "/api/autonoma")
  @app = app
  @config = enrich_config(config)
  @path = path
end

Instance Method Details

#call(env) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/autonoma_rails/server.rb', line 58

def call(env)
  unless env["PATH_INFO"] == @path && env["REQUEST_METHOD"] == "POST"
    return @app.call(env)
  end

  body_str = env["rack.input"].read
  env["rack.input"].rewind

  headers = {}
  env.each do |key, value|
    if key.start_with?("HTTP_")
      header_name = key[5..].downcase.tr("_", "-")
      headers[header_name] = value
    end
  end
  headers["content-type"] = env["CONTENT_TYPE"] if env["CONTENT_TYPE"]

  req = Autonoma::HandlerRequest.new(body: body_str, headers: headers)
  result = Autonoma::Handler.handle_request(@config, req)

  [
    result.status,
    { "Content-Type" => "application/json" },
    [JSON.generate(Autonoma::Refs.make_json_safe(result.body))]
  ]
end