Skip to content

Instantly share code, notes, and snippets.

@lukelex
Last active August 29, 2015 14:07
Show Gist options
  • Save lukelex/e038174bfcfc0492a83c to your computer and use it in GitHub Desktop.
Save lukelex/e038174bfcfc0492a83c to your computer and use it in GitHub Desktop.
class BatcherMiddleware
def initialize(app)
@app = app
end
def call(env)
if env["PATH_INFO"] == "/batch"
request = Rack::Request.new(env.deep_dup)
responses = JSON.parse(request[:requests]).map do |override|
process_request(env.deep_dup, override)
end
[200, {"Content-Type" => "application/json"}, [{responses: responses}.to_json]]
else
@app.call(env)
end
end
def process_request(env, override)
path, query = override["url"].split("?")
env["REQUEST_METHOD"] = override["method"]
env["PATH_INFO"] = path
options = env["rack.routing_args"][:route_info]
.instance_variable_get("@options")
.merge!(method: override["method"], path: path)
env["QUERY_STRING"] = query
env["rack.input"] = StringIO.new(override["body"].to_s)
status, headers, body = @app.call(env)
body.close
{status: status, headers: headers, body: body.body.join}
end
end
class Server < Grape::API
use BatcherMiddleware
# ...enpoints...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment