lib/grape/batch.rb in grape-batch-1.1.1 vs lib/grape/batch.rb in grape-batch-1.1.2

- old
+ new

@@ -1,10 +1,13 @@ +require 'active_support' +require 'grape/batch/log_subscriber' + +require 'grape/batch/version' require 'grape/batch/errors' require 'grape/batch/configuration' require 'grape/batch/parser' require 'grape/batch/response' -require 'grape/batch/version' require 'multi_json' module Grape module Batch class Base @@ -18,11 +21,11 @@ batch_call(env) end def batch_call(env) status = 200 - headers = {'Content-Type' => 'application/json'} + headers = { 'Content-Type' => 'application/json' } begin batch_requests = Grape::Batch::Validator::parse(env, Grape::Batch.configuration.limit) result = dispatch(env, batch_requests) body = MultiJson.encode(result) @@ -36,33 +39,47 @@ private def is_batch_request?(env) env['PATH_INFO'].start_with?(Grape::Batch.configuration.path) && - env['REQUEST_METHOD'] == 'POST' && - env['CONTENT_TYPE'] == 'application/json' + env['REQUEST_METHOD'] == 'POST' && + env['CONTENT_TYPE'] == 'application/json' end def dispatch(env, batch_requests) - request_env = env.dup + ActiveSupport::Notifications.instrument 'dispatch.batch' do |event| + event[:requests] = [] - batch_requests.map do |request| - method = request['method'] - path = request['path'] - body = request['body'].is_a?(Hash) ? request['body'] : {} + # iterate + batch_requests.map do |request| + # init env for Grape resource + tmp_env = prepare_tmp_env(env.dup, request) + status, headers, response = @app.call(tmp_env) - request_env['REQUEST_METHOD'] = method - request_env['PATH_INFO'] = path - if method == 'GET' - request_env['rack.input'] = StringIO.new('{}') - request_env['QUERY_STRING'] = URI.encode_www_form(body.to_a) - else - request_env['rack.input'] = StringIO.new(MultiJson.encode(body)) + # format response + @response_klass::format(status, headers, response).tap do |formatted_response| + # log call + event[:requests] << [tmp_env, formatted_response] + end end + end + end - status, headers, response = @app.call(request_env) + def prepare_tmp_env(tmp_env, request) + method = request['method'] + path = request['path'] + body = request['body'].is_a?(Hash) ? request['body'] : {} - @response_klass::format(status, headers, response) + tmp_env.tap do |env| + env['REQUEST_METHOD'] = method + env['PATH_INFO'] = path + + if method == 'GET' + env['rack.input'] = StringIO.new('{}') + env['QUERY_STRING'] = URI.encode_www_form(body.to_a) + else + env['rack.input'] = StringIO.new(MultiJson.encode(body)) + end end end end end end