├── .gitignore ├── .rspec ├── .rubocop.yml ├── .ruby-gemset ├── .ruby-version ├── .travis.yml ├── CHANGELOG.md ├── Gemfile ├── LICENSE.txt ├── README.md ├── Rakefile ├── grape-batch.gemspec ├── lib └── grape │ ├── batch.rb │ └── batch │ ├── base.rb │ ├── configuration.rb │ ├── converter.rb │ ├── errors.rb │ ├── logger.rb │ ├── request.rb │ ├── response.rb │ ├── validator.rb │ └── version.rb └── spec ├── api.rb ├── grape └── batch │ └── base_spec.rb └── spec_helper.rb /.gitignore: -------------------------------------------------------------------------------- 1 | *.gem 2 | *.rbc 3 | .bundle 4 | .config 5 | .yardoc 6 | Gemfile.lock 7 | InstalledFiles 8 | _yardoc 9 | coverage 10 | doc/ 11 | lib/bundler/man 12 | pkg 13 | rdoc 14 | spec/reports 15 | test/tmp 16 | test/version_tmp 17 | tmp 18 | *.bundle 19 | *.so 20 | *.o 21 | *.a 22 | mkmf.log 23 | 24 | # RubyMine 25 | .idea 26 | 27 | # OSX 28 | .DS_Store 29 | -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --color 2 | --require spec_helper 3 | --format documentation 4 | --order rand -------------------------------------------------------------------------------- /.rubocop.yml: -------------------------------------------------------------------------------- 1 | require: rubocop-rspec 2 | 3 | Metrics/LineLength: 4 | Max: 99 5 | 6 | # Indentation of `when`. 7 | Style/CaseIndentation: 8 | IndentWhenRelativeTo: case 9 | SupportedStyles: 10 | - case 11 | - end 12 | IndentOneStep: true 13 | -------------------------------------------------------------------------------- /.ruby-gemset: -------------------------------------------------------------------------------- 1 | grape-batch -------------------------------------------------------------------------------- /.ruby-version: -------------------------------------------------------------------------------- 1 | 2.2.2 -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: ruby 2 | rvm: 3 | - 2.2.2 4 | script: bundle exec rspec spec 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 2.3.0 (22nd March 2016) 2 | * Remove request session and token headers from response headers 3 | * Code refactor 4 | 5 | # 2.2.2 (22nd March 2016) 6 | * SESSION_HEADER is no longer duplicated because when the header contains an ActiveRecord object or something similar, it changes the object id 7 | 8 | # 2.2.1 (11th January 2016) 9 | * Fix main module NameError 10 | 11 | # 2.2.0 (11th January 2016) 12 | * Added authentication during request batch 13 | 14 | # 2.1.1 (5th November 2015) 15 | * Code refactoring to prepare next features 16 | 17 | # 2.1.0 (4th November 2015) 18 | * Removed error response format because of unexpected side effects 19 | 20 | # 2.0.1 (30th September 2015) 21 | * Removed obsolete gem dependencies 22 | * Now ensures the response is properly formatted and not empty, or returns an error 23 | 24 | # 2.0.0 (26rd August 2015) 25 | * Removed session_header from configuration options 26 | * Now passes the whole env to the session Proc 27 | 28 | # 1.2.1 (24rd July 2015) 29 | * Using env['HTTP_X_REQUEST_ID'] or env['rack-timeout.info'][:id] or generate unique hex to identify request batch 30 | 31 | # 1.2.0 (23rd July 2015) 32 | * Removed logging, added batch START and END logs 33 | 34 | # 1.1.4 (17th July 2015) 35 | * Added batch session 36 | 37 | # 1.1.3 (25th June 2015) 38 | * Fixed nested hash to url_encoded 39 | 40 | # 1.1.2 (17th February 2015) 41 | * Added logs 42 | 43 | # 1.1.1 (31st December 2014) 44 | * First stable version 45 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | # Specify your gem's dependencies in grape-batch.gemspec 4 | gemspec 5 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014 Lionel Oto 2 | 3 | MIT License 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining 6 | a copy of this software and associated documentation files (the 7 | "Software"), to deal in the Software without restriction, including 8 | without limitation the rights to use, copy, modify, merge, publish, 9 | distribute, sublicense, and/or sell copies of the Software, and to 10 | permit persons to whom the Software is furnished to do so, subject to 11 | the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be 14 | included in all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 20 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 22 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Grape::Batch 2 | 3 | Rack middleware which extends Grape::API to support request batching. 4 | 5 | ![Build status](https://travis-ci.org/c4mprod/grape-batch.svg?branch=master) 6 | 7 | ## Installation 8 | 9 | Add this line to your application's Gemfile: 10 | 11 | gem 'grape-batch' 12 | 13 | And then execute: 14 | 15 | $ bundle 16 | 17 | Or install it yourself as: 18 | 19 | $ gem install grape-batch 20 | 21 | ## Usage 22 | ### General considerations 23 | This middleware is intended to be used with JSON Grape::API only. 24 | 25 | ### Rails apps 26 | 1. Create an initializer and add you configuration 'config/initializers/grape-batch.rb' 27 | 2. Add the middleware to the stack 28 | ```ruby 29 | # config/application.rb 30 | Rails.application.configure do 31 | # rest of the file is hidden 32 | config.middleware.use Grape::Batch::Base 33 | end 34 | ``` 35 | 36 | ### Sinatra and other Rack apps 37 | ```ruby 38 | # config.ru 39 | require 'grape/batch' 40 | use Grape::Batch::Base 41 | ``` 42 | 43 | ### Settings 44 | Override any of these defaults in config/initializers/grape_batch.rb: 45 | 46 | ```ruby 47 | Grape::Batch.configure do |config| 48 | config.limit = 10 49 | config.path = '/batch' 50 | config.formatter = Grape::Batch::Response 51 | config.logger = nil 52 | config.session_proc = Proc.new {} 53 | end 54 | ``` 55 | 56 | | Argument | Type | Default | Description 57 | | :---: | :---: | :---: | :---: 58 | | limit | integer | 10 | Maximum number of batched requests allowed by the middleware 59 | | path | string | /batch | Route on which the middleware is mounted on 60 | | formatter | class | Grape::Batch::Response | The response formatter to use 61 | 62 | #### Response formatter 63 | #####Default format (success) 64 | ```ruby 65 | {success: RESOURCE_RESPONSE} 66 | ``` 67 | 68 | #####Default format (failure) 69 | ```ruby 70 | {code: HTTP_STATUS_CODE, error: ERROR_MESSAGE} 71 | ``` 72 | 73 | Can be inherited easily. 74 | ```ruby 75 | class MyFormatter < Grape::Batch::Response 76 | def self.format(status, headers, body) 77 | # My awesome formatting 78 | end 79 | end 80 | ``` 81 | 82 | ### Input format 83 | POST http request on the default URL with a similar body: 84 | ```ruby 85 | { 86 | requests: 87 | [ 88 | { 89 | method: 'GET', 90 | path: '/api/v1/users' 91 | }, 92 | { 93 | method: 'POST', 94 | path: '/api/v1/login', 95 | body: { token: 'nrg55xwrd45' } 96 | } 97 | ] 98 | } 99 | ``` 100 | 101 | 'body' is optional. 102 | 103 | ### Sessions 104 | #### Single authentication 105 | It's possible ensure a single session during the execution of the batch. You have to specify your session Proc. Before running the batch, the Proc is executed (with env as argument) and stored in rack env 'api.session' key. 106 | ```ruby 107 | # Example 108 | # Considering the config 109 | Grape::Batch.configure do |config| 110 | config.session_proc = Proc.new {|env| User.where(token: env['HTTP_X_TOKEN']).first } 111 | end 112 | 113 | # You can build a Grape helper like this 114 | module AuthHelpers 115 | def current_user 116 | if env['api.session'] 117 | env['api.session'] 118 | else 119 | # do authentication stuff 120 | end 121 | end 122 | end 123 | ``` 124 | 125 | #### Authentication during request batch 126 | It is possible to either keep a token (or a session) generated by a request of the batch and pass it to the following ones. 127 | ```ruby 128 | # Token example 129 | # Considering this API 130 | module Twitter 131 | class API < Grape::API 132 | version 'v1', using: :path 133 | format :json 134 | prefix 'api' 135 | 136 | resource :session do 137 | get do 138 | # route logic 139 | request.env['HTTP_X_API_TOKEN'] = 'my_fresh_token' 140 | # some other logic 141 | end 142 | end 143 | end 144 | 145 | # This route will register a token. The header will be kept and passed to the following requests by Grape::Batch. 146 | ``` 147 | 148 | ```ruby 149 | # Session example 150 | # Considering this API 151 | module Twitter 152 | class API < Grape::API 153 | version 'v1', using: :path 154 | format :json 155 | prefix 'api' 156 | 157 | resource :session do 158 | get do 159 | # route logic 160 | request.env['api.session'] = OpenStruct(id: '123456') 161 | # some other logic 162 | end 163 | end 164 | end 165 | 166 | # This route will return a session object. The session object will be kept and passed to the following requests by Grape::Batch. 167 | ``` 168 | 169 | ## Contributing 170 | 171 | 1. Fork it ( https://github.com/c4mprod/grape-batch/fork ) 172 | 2. Create your feature branch (`git checkout -b my-new-feature`) 173 | 3. Commit your changes (`git commit -am 'Add some feature'`) 174 | 4. Push to the branch (`git push origin my-new-feature`) 175 | 5. Create a new Pull Request 176 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | require 'bundler/gem_tasks' 2 | -------------------------------------------------------------------------------- /grape-batch.gemspec: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | lib = File.expand_path('../lib', __FILE__) 3 | $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) 4 | require 'grape/batch/version' 5 | 6 | Gem::Specification.new do |spec| 7 | spec.name = 'grape-batch' 8 | spec.version = Grape::Batch::VERSION 9 | spec.authors = ['Lionel Oto', 'Vincent Falduto', 'Cédric Darné'] 10 | spec.email = %w(lionel.oto@c4mprod.com 11 | vincent.falduto@c4mprod.com 12 | cedric.darne@c4mprod.com) 13 | spec.summary = 'Extends Grape::API to support request batching' 14 | spec.homepage = 'https://github.com/c4mprod/grape-batch' 15 | spec.license = 'MIT' 16 | 17 | spec.files = `git ls-files -z`.split("\x0") 18 | spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } 19 | spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) 20 | spec.require_paths = ['lib'] 21 | 22 | spec.add_runtime_dependency 'multi_json', '>= 1.0' 23 | 24 | spec.add_development_dependency 'bundler', '~> 1.6' 25 | spec.add_development_dependency 'grape', '>= 0.7.0' 26 | spec.add_development_dependency 'rack-test', '~> 0.6.2' 27 | spec.add_development_dependency 'rake', '~> 10.3.2' 28 | spec.add_development_dependency 'rspec', '~> 3.1.0' 29 | spec.add_development_dependency 'rubocop', '~> 0.34.2' 30 | spec.add_development_dependency 'rubocop-rspec', '~> 1.3.1' 31 | end 32 | -------------------------------------------------------------------------------- /lib/grape/batch.rb: -------------------------------------------------------------------------------- 1 | require 'grape/batch/configuration' 2 | require 'grape/batch/errors' 3 | require 'grape/batch/logger' 4 | require 'grape/batch/request' 5 | require 'grape/batch/response' 6 | require 'grape/batch/validator' 7 | require 'grape/batch/version' 8 | require 'grape/batch/base' 9 | require 'multi_json' 10 | 11 | module Grape 12 | module Batch 13 | 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /lib/grape/batch/base.rb: -------------------------------------------------------------------------------- 1 | module Grape 2 | module Batch 3 | class Base 4 | SESSION_HEADER = 'api.session'.freeze 5 | TOKEN_HEADER = 'HTTP_X_API_TOKEN'.freeze 6 | 7 | def initialize(app) 8 | @app = app 9 | @logger = Grape::Batch::Logger.new 10 | end 11 | 12 | def call(env) 13 | return @app.call(env) unless batch_request?(env) 14 | 15 | # Handle batch requests 16 | @logger.prepare(env).batch_begin 17 | body, status = batch_call(env) 18 | @logger.batch_end 19 | 20 | # Return Rack formatted response 21 | Rack::Response.new(body, status, 'Content-Type' => 'application/json') 22 | end 23 | 24 | def batch_call(env) 25 | batch_requests = Grape::Batch::Validator.parse(env, Grape::Batch.configuration.limit) 26 | [MultiJson.encode(dispatch(env, batch_requests)), 200] 27 | 28 | rescue Grape::Batch::RequestBodyError, Grape::Batch::TooManyRequestsError => e 29 | [e.message, e.class == TooManyRequestsError ? 429 : 400] 30 | end 31 | 32 | def dispatch(env, batch_requests) 33 | call_api_session_proc(env) 34 | 35 | # Call batch request 36 | batch_requests.map do |batch_request| 37 | batch_env = Grape::Batch::Request.new(env, batch_request).build 38 | call_batched_request(batch_env) 39 | end 40 | end 41 | 42 | def call_batched_request(env) 43 | status, headers, response = @app.call(env) 44 | Grape::Batch.configuration.formatter.format(status, headers, response) 45 | end 46 | 47 | private 48 | 49 | def batch_request?(env) 50 | env['PATH_INFO'].start_with?(Grape::Batch.configuration.path) && 51 | env['REQUEST_METHOD'] == 'POST' && env['CONTENT_TYPE'] == 'application/json' 52 | end 53 | 54 | def call_api_session_proc(env) 55 | return unless Grape::Batch.configuration.session_proc 56 | env[SESSION_HEADER] = Grape::Batch.configuration.session_proc.call(env) 57 | end 58 | end 59 | end 60 | end 61 | -------------------------------------------------------------------------------- /lib/grape/batch/configuration.rb: -------------------------------------------------------------------------------- 1 | module Grape 2 | # Main gem module 3 | module Batch 4 | # Gem configuration 5 | class Configuration 6 | attr_accessor :path, :limit, :formatter, :logger, :session_proc 7 | 8 | def initialize 9 | @path = '/batch' 10 | @limit = 10 11 | @formatter = Grape::Batch::Response 12 | @logger = nil 13 | @session_proc = nil 14 | end 15 | end 16 | 17 | # Set default configuration for Grape::Batch middleware 18 | class << self 19 | attr_accessor :configuration 20 | end 21 | 22 | def self.configuration 23 | @configuration ||= Configuration.new 24 | end 25 | 26 | def self.configuration=(config) 27 | @configuration = config 28 | end 29 | 30 | def self.configure 31 | yield configuration 32 | end 33 | end 34 | end 35 | -------------------------------------------------------------------------------- /lib/grape/batch/converter.rb: -------------------------------------------------------------------------------- 1 | module Grape 2 | module Batch 3 | # Convert hash to www form url params 4 | class Converter 5 | class << self 6 | def encode(value, key = nil, out_hash = {}) 7 | case value 8 | when Hash 9 | value.each { |k, v| encode(v, append_key(key, k), out_hash) } 10 | when Array 11 | value.each { |v| encode(v, "#{key}[]", out_hash) } 12 | else 13 | out_hash[key] = value 14 | end 15 | 16 | value ? out_hash : '' 17 | end 18 | 19 | def append_key(root_key, key) 20 | root_key ? :"#{root_key}[#{key.to_s}]" : :"#{key}" 21 | end 22 | end 23 | end 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /lib/grape/batch/errors.rb: -------------------------------------------------------------------------------- 1 | module Grape 2 | module Batch 3 | class RequestBodyError < ArgumentError 4 | # Request body is blank 5 | class Blank < RequestBodyError 6 | def initialize 7 | super('Request body is blank') 8 | end 9 | end 10 | 11 | # Request body is not properly formatted JSON 12 | class JsonFormat < RequestBodyError 13 | def initialize 14 | super('Request body is not valid JSON') 15 | end 16 | end 17 | 18 | # Batch body is nil 19 | class Nil < RequestBodyError 20 | def initialize 21 | super('Request body is nil') 22 | end 23 | end 24 | 25 | # Batch body isn't properly formatted as a Hash 26 | class Format < RequestBodyError 27 | def initialize 28 | super('Request body is not well formatted') 29 | end 30 | end 31 | 32 | # Some requests attributes are missing in the batch body 33 | class MissingRequests < RequestBodyError 34 | def initialize 35 | super("'requests' object is missing in request body") 36 | end 37 | end 38 | 39 | # Some requests attributes aren't properly formatted as an Array 40 | class RequestFormat < RequestBodyError 41 | def initialize 42 | super("'requests' is not well formatted") 43 | end 44 | end 45 | 46 | # Batch request method is missing 47 | class MissingMethod < RequestBodyError 48 | def initialize 49 | super("'method' is missing in one of request objects") 50 | end 51 | end 52 | 53 | # Batch request method isn't properly formatted as a String 54 | class MethodFormat < RequestBodyError 55 | def initialize 56 | super("'method' is invalid in one of request objects") 57 | end 58 | end 59 | 60 | # Batch request method aren't allowed 61 | class InvalidMethod < RequestBodyError 62 | def initialize 63 | super("'method' is invalid in one of request objects") 64 | end 65 | end 66 | 67 | # Batch request path is missing 68 | class MissingPath < RequestBodyError 69 | def initialize 70 | super("'path' is missing in one of request objects") 71 | end 72 | end 73 | 74 | # Batch request path isn't properly formatted as a String 75 | class InvalidPath < RequestBodyError 76 | def initialize 77 | super("'path' is invalid in one of request objects") 78 | end 79 | end 80 | end 81 | 82 | # Batch exceeds request limit 83 | class TooManyRequestsError < StandardError 84 | def initialize 85 | super('Batch requests limit exceeded') 86 | end 87 | end 88 | end 89 | end 90 | -------------------------------------------------------------------------------- /lib/grape/batch/logger.rb: -------------------------------------------------------------------------------- 1 | module Grape 2 | module Batch 3 | # Main class logger 4 | class Logger 5 | def prepare(env) 6 | rack_timeout_info = env['rack-timeout.info'][:id] if env['rack-timeout.info'] 7 | @request_id = env['HTTP_X_REQUEST_ID'] || rack_timeout_info || SecureRandom.hex 8 | @logger = Grape::Batch.configuration.logger || rails_logger || default_logger 9 | self 10 | end 11 | 12 | def default_logger 13 | logger = Logger.new($stdout) 14 | logger.level = Logger::INFO 15 | logger 16 | end 17 | 18 | def rails_logger 19 | defined?(::Rails) && ::Rails.respond_to?(:logger) && ::Rails.logger 20 | end 21 | 22 | def batch_begin 23 | @logger.info("--- Grape::Batch #{@request_id} BEGIN") 24 | self 25 | end 26 | 27 | def batch_end 28 | @logger.info("--- Grape::Batch #{@request_id} END") 29 | self 30 | end 31 | end 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /lib/grape/batch/request.rb: -------------------------------------------------------------------------------- 1 | require 'grape/batch/converter' 2 | 3 | module Grape 4 | module Batch 5 | # Prepare batch request 6 | class Request 7 | def initialize(env, batch_request) 8 | @env = env 9 | @batch_request = batch_request 10 | end 11 | 12 | def method 13 | @batch_request['method'] 14 | end 15 | 16 | def path 17 | @batch_request['path'] 18 | end 19 | 20 | def body 21 | @body ||= @batch_request['body'].is_a?(Hash) ? @batch_request['body'] : {} 22 | end 23 | 24 | def query_string 25 | @query_string ||= method == 'GET' ? URI.encode_www_form(Converter.encode(body).to_a) : '' 26 | end 27 | 28 | def rack_input 29 | @rack_input ||= method == 'GET' ? '{}' : StringIO.new(MultiJson.encode(body)) 30 | end 31 | 32 | def build 33 | @env['REQUEST_METHOD'] = method 34 | @env['PATH_INFO'] = path 35 | @env['QUERY_STRING'] = query_string 36 | @env['rack.input'] = rack_input 37 | @env 38 | end 39 | end 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /lib/grape/batch/response.rb: -------------------------------------------------------------------------------- 1 | module Grape 2 | module Batch 3 | # Format batch request response 4 | class Response 5 | def self.format(status, _headers, response) 6 | if response 7 | body = response.respond_to?(:body) ? response.body.join : response.join 8 | result = MultiJson.decode(body) 9 | end 10 | 11 | if (200..299).include?(status) 12 | { success: result } 13 | else 14 | { code: status, error: result['error'] } 15 | end 16 | end 17 | end 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /lib/grape/batch/validator.rb: -------------------------------------------------------------------------------- 1 | module Grape 2 | module Batch 3 | # Parse and validate request params and ensure it is a valid batch request 4 | class Validator 5 | ALLOWED_METHODS = %w(GET DELETE PATCH POST PUT) 6 | 7 | class << self 8 | def parse(env, limit) 9 | batch_body = decode_body(env['rack.input'].read) 10 | 11 | requests = batch_body['requests'] 12 | validate_batch(requests, limit) 13 | requests.each { |request| validate_request(request) } 14 | 15 | requests 16 | end 17 | 18 | private 19 | 20 | def decode_body(body) 21 | fail RequestBodyError::Blank unless body.length > 0 22 | 23 | begin 24 | batch_body = MultiJson.decode(body) 25 | rescue MultiJson::ParseError 26 | raise RequestBodyError::JsonFormat 27 | end 28 | 29 | fail RequestBodyError::Nil unless batch_body 30 | fail RequestBodyError::Format unless batch_body.is_a?(Hash) 31 | 32 | batch_body 33 | end 34 | 35 | def validate_batch(batch_requests, limit) 36 | fail RequestBodyError::MissingRequests unless batch_requests 37 | fail RequestBodyError::RequestFormat unless batch_requests.is_a?(Array) 38 | fail TooManyRequestsError if batch_requests.count > limit 39 | end 40 | 41 | def validate_request(request) 42 | fail RequestBodyError::MissingMethod unless request['method'] 43 | fail RequestBodyError::MethodFormat unless request['method'].is_a?(String) 44 | fail RequestBodyError::InvalidMethod unless ALLOWED_METHODS.include?(request['method']) 45 | fail RequestBodyError::MissingPath unless request['path'] 46 | fail RequestBodyError::InvalidPath unless request['path'].is_a?(String) 47 | end 48 | end 49 | end 50 | end 51 | end 52 | -------------------------------------------------------------------------------- /lib/grape/batch/version.rb: -------------------------------------------------------------------------------- 1 | module Grape 2 | # Gem main module 3 | module Batch 4 | VERSION = '2.3.0' 5 | end 6 | end 7 | -------------------------------------------------------------------------------- /spec/api.rb: -------------------------------------------------------------------------------- 1 | module Twitter 2 | class API < Grape::API 3 | version 'v1', using: :path 4 | format :json 5 | prefix 'api' 6 | 7 | resource :hello do 8 | get do 9 | 'world' 10 | end 11 | 12 | post do 13 | 'world' 14 | end 15 | end 16 | 17 | resource :failure do 18 | desc 'Failure' 19 | get do 20 | error!('Failed as expected', 503) 21 | end 22 | end 23 | 24 | resource :user do 25 | params do 26 | requires :id, type: Integer, desc: 'User id.' 27 | end 28 | route_param :id do 29 | get do 30 | "user #{params[:id]}" 31 | end 32 | end 33 | end 34 | 35 | resource :complex do 36 | params do 37 | requires :a, type: Hash 38 | end 39 | get do 40 | "hash #{params[:a][:b][:c]}" 41 | end 42 | end 43 | 44 | resource :status do 45 | params do 46 | requires :id, type: Integer, desc: 'User id.' 47 | end 48 | get do 49 | "status #{params[:id]}" 50 | end 51 | 52 | params do 53 | requires :id, type: Integer, desc: 'User id.' 54 | end 55 | post do 56 | "status #{params[:id]}" 57 | end 58 | end 59 | 60 | resource :login do 61 | get do 62 | request.env['HTTP_X_API_TOKEN'] = 'user_token' 63 | 64 | 'login successful' 65 | end 66 | 67 | post do 68 | if env['HTTP_X_API_TOKEN'] == 'user_token' 69 | 'token valid' 70 | else 71 | 'token invalid' 72 | end 73 | end 74 | end 75 | 76 | resource :session do 77 | get do 78 | request.env['api.session'] = OpenStruct.new(nick: 'Bob') 79 | 80 | 'session reloaded' 81 | end 82 | 83 | post do 84 | if env['api.session'] && env['api.session'].nick == 'Bob' 85 | 'session valid' 86 | else 87 | 'session invalid' 88 | end 89 | end 90 | end 91 | 92 | # 404 93 | # 94 | route :any, '*path' do 95 | error!("#{@env['PATH_INFO']} not found", 404) 96 | end 97 | end 98 | end 99 | -------------------------------------------------------------------------------- /spec/grape/batch/base_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | require 'rack/test' 3 | require 'grape' 4 | require 'grape/batch' 5 | require 'api' 6 | 7 | RSpec.describe Grape::Batch::Base do 8 | before(:all) do 9 | Grape::Batch.configuration.logger = Logger.new('/dev/null') 10 | end 11 | 12 | before :context do 13 | @app = Twitter::API.new 14 | end 15 | 16 | let(:stack) { described_class.new(@app) } 17 | let(:request) { Rack::MockRequest.new(stack) } 18 | 19 | def encode(message) 20 | MultiJson.encode(message) 21 | end 22 | 23 | def decode(message) 24 | MultiJson.decode(message) 25 | end 26 | 27 | describe '/api' do 28 | describe 'GET /hello' do 29 | let(:response) { request.get('/api/v1/hello') } 30 | 31 | it { expect(response.status).to eq(200) } 32 | it { expect(response.body).to eq(encode('world')) } 33 | end 34 | 35 | describe 'GET /failure' do 36 | let(:response) { request.get('/api/v1/failure') } 37 | it { expect(response.status).to eq(503) } 38 | it { expect(response.body).to eq(encode(error: 'Failed as expected')) } 39 | end 40 | end 41 | 42 | describe '/batch' do 43 | let(:request_body) { nil } 44 | let(:options) { { 'CONTENT_TYPE' => 'application/json', input: request_body } } 45 | let(:response) { request.post('/batch', options) } 46 | 47 | context 'with invalid body' do 48 | it { expect(response.status).to eq(400) } 49 | 50 | context 'when body == nil' do 51 | it { expect(response.body).to eq('Request body is blank') } 52 | end 53 | 54 | context 'when body is empty' do 55 | let(:request_body) { '' } 56 | it { expect(response.body).to eq('Request body is blank') } 57 | end 58 | 59 | context 'when body is not valid JSON' do 60 | let(:request_body) { 'ads[}' } 61 | it { expect(response.body).to eq('Request body is not valid JSON') } 62 | end 63 | 64 | context 'when body == null' do 65 | let(:request_body) { 'null' } 66 | it { expect(response.body).to eq('Request body is nil') } 67 | end 68 | 69 | context 'when body is not a hash' do 70 | let(:request_body) { '[1, 2, 3]' } 71 | it { expect(response.body).to eq('Request body is not well formatted') } 72 | end 73 | 74 | context "when body['requests'] == nil" do 75 | let(:request_body) { '{}' } 76 | it { expect(response.body).to eq("'requests' object is missing in request body") } 77 | end 78 | 79 | context "when body['requests'] is not an array" do 80 | let(:request_body) { encode(requests: 'request') } 81 | it { expect(response.body).to eq("'requests' is not well formatted") } 82 | end 83 | 84 | context 'when request limit is exceeded' do 85 | let(:request_body) { encode(requests: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) } 86 | it { expect(response.body).to eq('Batch requests limit exceeded') } 87 | end 88 | 89 | describe 'method attribute in request object' do 90 | context 'method is missing' do 91 | let(:request_body) { encode(requests: [{}]) } 92 | it { expect(response.body).to eq("'method' is missing in one of request objects") } 93 | end 94 | 95 | context 'method is not a String' do 96 | let(:request_body) { encode(requests: [{ method: true }]) } 97 | it { expect(response.body).to eq("'method' is invalid in one of request objects") } 98 | end 99 | 100 | context 'method is invalid' do 101 | let(:request_body) { encode(requests: [{ method: 'TRACE' }]) } 102 | it { expect(response.body).to eq("'method' is invalid in one of request objects") } 103 | end 104 | end 105 | 106 | describe 'path attribute in request object' do 107 | context 'path is missing' do 108 | let(:request_body) { encode(requests: [{ method: 'GET' }]) } 109 | it { expect(response.body).to eq("'path' is missing in one of request objects") } 110 | end 111 | 112 | context 'path is not a String' do 113 | let(:request_body) { encode(requests: [{ method: 'GET', path: 123 }]) } 114 | it { expect(response.body).to eq("'path' is invalid in one of request objects") } 115 | end 116 | end 117 | end 118 | 119 | describe 'GET' do 120 | context 'with no parameters' do 121 | let(:request_body) { encode(requests: [{ method: 'GET', path: '/api/v1/hello' }]) } 122 | it { expect(response.status).to eq(200) } 123 | it { expect(response.body).to eq(encode([{ success: 'world' }])) } 124 | end 125 | 126 | context 'with parameters' do 127 | let(:request_body) { encode(requests: [{ method: 'GET', path: '/api/v1/user/856' }]) } 128 | it { expect(response.status).to eq(200) } 129 | it { expect(response.body).to eq(encode([{ success: 'user 856' }])) } 130 | end 131 | 132 | context 'with a body' do 133 | let(:path) { '/api/v1/status' } 134 | let(:request_body) { encode(requests: [{ method: 'GET', path: path, body: { id: 856 } }]) } 135 | it { expect(response.status).to eq(200) } 136 | it { expect(response.body).to eq(encode([{ success: 'status 856' }])) } 137 | end 138 | 139 | context 'with a body and nested hash' do 140 | let(:path) { '/api/v1/complex' } 141 | let(:complex) { { a: { b: { c: 1 } } } } 142 | let(:request_body) { encode(requests: [{ method: 'GET', path: path, body: complex }]) } 143 | it { expect(response.status).to eq(200) } 144 | it { expect(response.body).to eq(encode([{ success: 'hash 1' }])) } 145 | end 146 | 147 | describe '404 errors' do 148 | let(:request_body) { encode(requests: [{ method: 'GET', path: '/api/v1/unknown' }]) } 149 | let(:expected_error) { { code: 404, error: '/api/v1/unknown not found' } } 150 | it { expect(response.status).to eq(200) } 151 | it { expect(response.body).to eq(encode([expected_error])) } 152 | end 153 | end 154 | 155 | describe 'POST' do 156 | context 'with no parameters' do 157 | let(:request_body) { encode(requests: [{ method: 'POST', path: '/api/v1/hello' }]) } 158 | it { expect(response.status).to eq(200) } 159 | it { expect(response.body).to eq(encode([{ success: 'world' }])) } 160 | end 161 | 162 | context 'with a body' do 163 | let(:path) { '/api/v1/status' } 164 | let(:body) { { id: 856 } } 165 | let(:request_body) { encode(requests: [{ method: 'POST', path: path, body: body }]) } 166 | it { expect(response.status).to eq(200) } 167 | it { expect(response.body).to eq(encode([{ success: 'status 856' }])) } 168 | end 169 | end 170 | 171 | describe 'POST' do 172 | context 'with multiple requests' do 173 | let(:request_1) { { method: 'POST', path: '/api/v1/hello' } } 174 | let(:request_2) { { method: 'GET', path: '/api/v1/user/856' } } 175 | let(:request_body) { encode(requests: [request_1, request_2]) } 176 | it { expect(response.status).to eq(200) } 177 | it { expect(decode(response.body).size).to eq(2) } 178 | end 179 | end 180 | 181 | describe 'single session' do 182 | describe 'without token' do 183 | let(:request_1) { { method: 'POST', path: '/api/v1/login' } } 184 | let(:request_body) { encode(requests: [request_1]) } 185 | it { expect(response.status).to eq(200) } 186 | it { expect(response.body).to eq(encode([{ success: 'token invalid' }])) } 187 | it { expect(response.headers).to_not include('HTTP_X_API_TOKEN') } 188 | end 189 | 190 | describe 'with a token' do 191 | let(:request_1) { { method: 'GET', path: '/api/v1/login' } } 192 | let(:request_2) { { method: 'POST', path: '/api/v1/login' } } 193 | let(:request_body) { encode(requests: [request_1, request_2]) } 194 | let(:expected_response) { [{ success: 'login successful' }, { success: 'token valid' }] } 195 | it { expect(response.status).to eq(200) } 196 | it { expect(response.body).to eq(encode(expected_response)) } 197 | it { expect(response.headers).to_not include('HTTP_X_API_TOKEN') } 198 | end 199 | 200 | describe 'without session' do 201 | let(:request_1) { { method: 'POST', path: '/api/v1/session' } } 202 | let(:request_body) { encode(requests: [request_1]) } 203 | it { expect(response.status).to eq(200) } 204 | it { expect(response.body).to eq(encode([{ success: 'session invalid' }])) } 205 | it { expect(response.headers).to_not include('api.session') } 206 | end 207 | 208 | describe 'with a session' do 209 | let(:request_1) { { method: 'GET', path: '/api/v1/session' } } 210 | let(:request_2) { { method: 'POST', path: '/api/v1/session' } } 211 | let(:request_body) { encode(requests: [request_1, request_2]) } 212 | let(:expected_response) { [{ success: 'session reloaded' }, { success: 'session valid' }] } 213 | it { expect(response.status).to eq(200) } 214 | it { expect(response.body).to eq(encode(expected_response)) } 215 | it { expect(response.headers).to_not include('api.session') } 216 | end 217 | end 218 | end 219 | 220 | describe '#configure' do 221 | it { expect(Grape::Batch.configuration).to_not be_nil } 222 | 223 | describe 'default_value' do 224 | it { expect(Grape::Batch.configuration.path).to eq('/batch') } 225 | it { expect(Grape::Batch.configuration.formatter).to eq(Grape::Batch::Response) } 226 | it { expect(Grape::Batch.configuration.limit).to eq(10) } 227 | end 228 | 229 | describe '.configure' do 230 | before do 231 | allow(Grape::Batch).to receive(:configuration) do 232 | config = Grape::Batch::Configuration.new 233 | config.path = '/custom_path' 234 | config.limit = 15 235 | config.session_proc = proc { 3 + 2 } 236 | config 237 | end 238 | end 239 | 240 | describe 'default_value' do 241 | it { expect(Grape::Batch.configuration.path).to eq('/custom_path') } 242 | it { expect(Grape::Batch.configuration.limit).to eq(15) } 243 | it { expect(Grape::Batch.configuration.session_proc.call).to eq(5) } 244 | end 245 | end 246 | end 247 | end 248 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # This file was generated by the `rails generate rspec:install` command. Conventionally, all 2 | # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. 3 | # The generated `.rspec` file contains `--require spec_helper` which will cause this 4 | # file to always be loaded, without a need to explicitly require it in any files. 5 | # 6 | # Given that it is always loaded, you are encouraged to keep this file as 7 | # light-weight as possible. Requiring heavyweight dependencies from this file 8 | # will add to the boot time of your test suite on EVERY test run, even for an 9 | # individual file that may not need all of that loaded. Instead, consider making 10 | # a separate helper file that requires the additional dependencies and performs 11 | # the additional setup, and require it from the spec files that actually need it. 12 | # 13 | # The `.rspec` file also contains a few flags that are not defaults but that 14 | # users commonly want. 15 | # 16 | # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration 17 | RSpec.configure do |config| 18 | # rspec-expectations config goes here. You can use an alternate 19 | # assertion/expectation library such as wrong or the stdlib/minitest 20 | # assertions if you prefer. 21 | config.expect_with :rspec do |expectations| 22 | # This option will default to `true` in RSpec 4. It makes the `description` 23 | # and `failure_message` of custom matchers include text for helper methods 24 | # defined using `chain`, e.g.: 25 | # be_bigger_than(2).and_smaller_than(4).description 26 | # # => "be bigger than 2 and smaller than 4" 27 | # ...rather than: 28 | # # => "be bigger than 2" 29 | expectations.include_chain_clauses_in_custom_matcher_descriptions = true 30 | end 31 | 32 | # rspec-mocks config goes here. You can use an alternate test double 33 | # library (such as bogus or mocha) by changing the `mock_with` option here. 34 | config.mock_with :rspec do |mocks| 35 | # Prevents you from mocking or stubbing a method that does not exist on 36 | # a real object. This is generally recommended, and will default to 37 | # `true` in RSpec 4. 38 | mocks.verify_partial_doubles = true 39 | end 40 | 41 | # The settings below are suggested to provide a good initial experience 42 | # with RSpec, but feel free to customize to your heart's content. 43 | # These two settings work together to allow you to limit a spec run 44 | # to individual examples or groups you care about by tagging them with 45 | # `:focus` metadata. When nothing is tagged with `:focus`, all examples 46 | # get run. 47 | # config.filter_run :focus 48 | # config.run_all_when_everything_filtered = true 49 | 50 | # Limits the available syntax to the non-monkey patched syntax that is recommended. 51 | # For more details, see: 52 | # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax 53 | # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ 54 | # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching 55 | # config.disable_monkey_patching! 56 | 57 | # Many RSpec users commonly either run the entire suite or an individual 58 | # file, and it's useful to allow more verbose output when running an 59 | # individual spec file. 60 | # if config.files_to_run.one? 61 | # Use the documentation formatter for detailed output, 62 | # unless a formatter has already been configured 63 | # (e.g. via a command-line flag). 64 | # config.default_formatter = 'doc' 65 | # end 66 | 67 | # Print the 10 slowest examples and example groups at the 68 | # end of the spec run, to help surface which specs are running 69 | # particularly slow. 70 | # config.profile_examples = 10 71 | 72 | # Run specs in random order to surface order dependencies. If you find an 73 | # order dependency and want to debug it, you can fix the order by providing 74 | # the seed, which is printed after each run. 75 | # --seed 1234 76 | config.order = :random 77 | 78 | # Seed global randomization in this process using the `--seed` CLI option. 79 | # Setting this allows you to use `--seed` to deterministically reproduce 80 | # test failures related to randomization by passing the same `--seed` value 81 | # as the one that triggered the failure. 82 | # Kernel.srand config.seed 83 | end 84 | --------------------------------------------------------------------------------