Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to integrate batch requests in a Rails API?

I'm building an API with Rails 4 and I really want to create a Batch request method to not overload my app when doing a bunch of ajax requests.

The Railscasts shows how to do it in a simple way but there's a lot of stuff missing.

I also tried the batch_api gem but I wasn't successful integrating it with my application.

Any ideas?

like image 741
Rafael Fragoso Avatar asked Oct 20 '22 09:10

Rafael Fragoso


1 Answers

I know it's being late to answer this question but I recently used batch_api gem with my Rails API (rails 5.0.0 and Ruby 2.0) and it works find with me.

What you need to do is follow the instruction of this document: https://github.com/arsduo/batch_api

Shortly:

1- You need to add the batch_api gem to your application GemFile.

2- You need to add the required middleware configuration in you application.rb file:

config.middleware.use BatchApi::RackMiddleware do |batch_config|
  # you can set various configuration options:
  batch_config.verb = :put # default :post
  batch_config.endpoint = "/batchapi" # default /batch
  batch_config.limit = 100 # how many operations max per request, default 50

  # default middleware stack run for each batch request
   batch_config.batch_middleware = Proc.new { }
  # default middleware stack run for each individual operation
  batch_config.operation_middleware = Proc.new { }
end

3- Then restart your rails server.

Make sure to insert the new middleware in the appropriate location, in my case I needed to include it before "ActionDispatch::RequestId" middleware.

config.middleware.insert_before "ActionDispatch::RequestId", BatchApi::RackMiddleware

because I wanted to include X-Request-ID header in each request in the Batch request and this ID will be returned in each response so that I could know the response for each request in the Batch (note that the responses will be executed sequentially depending on the sequence each request in the Batch).

like image 174
Alanoud Just Avatar answered Nov 01 '22 10:11

Alanoud Just