Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
tuwilof committed Jan 27, 2017
0 parents commit 3f6d5b8
Show file tree
Hide file tree
Showing 25 changed files with 695 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.idea/
.byebug_history
*.gem
*.log
spec/integration/apps/rails_app/log
Gemfile.lock
coverage
11 changes: 11 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
AllCops:
TargetRubyVersion: 2.3

Metrics/LineLength:
Max: 120

Style/Documentation:
Enabled: false

Style/FrozenStringLiteralComment:
Enabled: false
1 change: 1 addition & 0 deletions .ruby-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
2.3.1
49 changes: 49 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Contributor Code of Conduct

As contributors and maintainers of this project, and in the interest of
fostering an open and welcoming community, we pledge to respect all people who
contribute through reporting issues, posting feature requests, updating
documentation, submitting pull requests or patches, and other activities.

We are committed to making participation in this project a harassment-free
experience for everyone, regardless of level of experience, gender, gender
identity and expression, sexual orientation, disability, personal appearance,
body size, race, ethnicity, age, religion, or nationality.

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery
* Personal attacks
* Trolling or insulting/derogatory comments
* Public or private harassment
* Publishing other's private information, such as physical or electronic
addresses, without explicit permission
* Other unethical or unprofessional conduct

Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.

By adopting this Code of Conduct, project maintainers commit themselves to
fairly and consistently applying these principles to every aspect of managing
this project. Project maintainers who do not follow or enforce the Code of
Conduct may be permanently removed from the project team.

This code of conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community.

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting a project maintainer at d.efimov@fun-box.ru. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. Maintainers are
obligated to maintain confidentiality with regard to the reporter of an
incident.

This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 1.3.0, available at
[http://contributor-covenant.org/version/1/3/0/][version]

[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/3/0/
3 changes: 3 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
source 'https://rubygems.org'

gemspec
21 changes: 21 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2016 d.efimov

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
83 changes: 83 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Esplanade

This gem helps you validate the request and response documentation API Blueprint.


If the request to the server will be invalid tomogram, it will return a response with a 400 status and the body of the error.
If the server's response will be invalid tomogram, it will return a response with 500 status and the body of the error.

An example of an error body

```ruby
{
"error": [
"The property '#/' did not contain a required property of 'login' in schema deee53ed-f917-5f2f-bccf-0b8af3b749c7",
"The property '#/' did not contain a required property of 'password' in schema deee53ed-f917-5f2f-bccf-0b8af3b749c7"
]
}
```

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'esplanade'
```

And then execute:

$ bundle

Or install it yourself as:

$ gem install esplanade

## Usage

### Rails

config/application.rb

```ruby
require 'esplanade'
```

### Rake

config/application.rb

```ruby
require 'esplanade'
config.middleware.use Esplanade::Middleware
```

## Config

### tomogram

This gem takes a simplified format json convert from API Blueprint which we have called API Tomogram.

If in your project you are using the gem tomograph, then define the configuration you are not required.

```ruby
Esplanade.configure do |config|
config.tomogram = 'tomogram.json'
end
```

### skip_not_documented

Default true.

### validation_requests

Default true.

### validation_response

Default true.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
6 changes: 6 additions & 0 deletions Rakefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
require 'bundler/gem_tasks'
require 'rspec/core/rake_task'

RSpec::Core::RakeTask.new(:spec)

task default: :spec
14 changes: 14 additions & 0 deletions bin/console
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#!/usr/bin/env ruby

require 'bundler/setup'
require 'esplanade'

# You can add fixtures and/or initialization code here to make experimenting
# with your gem easier. You can also use a different console, if you like.

# (If you use this, don't forget to add pry to your Gemfile!)
# require "pry"
# Pry.start

require 'irb'
IRB.start
8 changes: 8 additions & 0 deletions bin/setup
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
set -vx

bundle install

# Do any other automated setup that you need to do here
29 changes: 29 additions & 0 deletions esplanade.gemspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'esplanade/version'

Gem::Specification.new do |spec|
spec.name = 'esplanade'
spec.version = Esplanade::VERSION
spec.authors = ['d.efimov']
spec.email = ['d.efimov@fun-box.ru']

spec.summary = 'Validate requests and responses against API Blueprint specifications'
spec.license = 'MIT'

spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']

spec.add_runtime_dependency 'multi_json', '~> 1.11', '>= 1.11.1'
spec.add_runtime_dependency 'json-schema', '~> 2.6', '>= 2.6.2'
spec.add_runtime_dependency 'tomogram_routing', '~> 0.1', '>= 0.1.0'
spec.add_development_dependency 'bundler', '~> 1.12'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'byebug', '~> 8.2', '>= 8.2.1'
spec.add_development_dependency 'rspec', '~> 3.4', '>= 3.4.0'
spec.add_development_dependency 'rubocop', '~> 0.42', '>= 0.42.0'
spec.add_development_dependency 'simplecov', '~> 0.11', '>= 0.11.2'
end
22 changes: 22 additions & 0 deletions lib/esplanade.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
require 'esplanade/middleware'
require 'esplanade/configuration'
require 'esplanade/request'
require 'esplanade/request/body'
require 'esplanade/request/error'
require 'esplanade/response'
require 'esplanade/response/body'
require 'esplanade/response/error'
require 'esplanade/railtie' if defined?(Rails)
require 'tomogram_routing'

module Esplanade
class << self
def configure
yield configuration
end

def configuration
@configuration ||= Configuration.new
end
end
end
14 changes: 14 additions & 0 deletions lib/esplanade/configuration.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module Esplanade
class Configuration
attr_accessor :tomogram,
:skip_not_documented,
:validation_requests,
:validation_response

def initialize
@skip_not_documented = true
@validation_requests = true
@validation_response = true
end
end
end
34 changes: 34 additions & 0 deletions lib/esplanade/middleware.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
require 'yaml'

module Esplanade
class Middleware
class Exit < RuntimeError; end
class ResponseNotDoc < RuntimeError; end

def initialize(app)
@app = app
@tomogram = TomogramRouting::Tomogram.craft(Esplanade.configuration.tomogram)
end

def call(env)
valid!(env)
rescue Request::NotDocumented
Request::Error.not_documented
rescue Response::NotDocumented
Response::Error.not_documented
rescue Request::Unsuitable => e
Request::Error.unsuitable(e.message)
rescue Response::Unsuitable => e
Response::Error.unsuitable(e.message)
end

def valid!(env)
request = Request.new(env, @tomogram)
request.valid! if request.validate?
status, headers, body = @app.call(env)
response = Response.new(status, body, request.schema)
response.valid! if response.validate?
[status, headers, body]
end
end
end
7 changes: 7 additions & 0 deletions lib/esplanade/railtie.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module Esplanade
class Railtie < Rails::Railtie
initializer 'esplanade.insert_middleware' do |app|
app.config.middleware.use Esplanade::Middleware
end
end
end
31 changes: 31 additions & 0 deletions lib/esplanade/request.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
require 'json-schema'

module Esplanade
class Request
attr_accessor :path, :method, :body, :schema

class Unsuitable < RuntimeError; end
class NotDocumented < RuntimeError; end

def initialize(env, tomogram)
@method = env['REQUEST_METHOD']
@path = env['PATH_INFO']
@body = Body.craft(env)
@schema = tomogram.find_request(method: @method, path: @path)
raise NotDocumented unless schema || Esplanade.configuration.skip_not_documented
self
end

def error
JSON::Validator.fully_validate(@schema['request'], @body)
end

def valid!
raise Unsuitable, error unless error.empty?
end

def validate?
@schema && Esplanade.configuration.validation_requests
end
end
end
14 changes: 14 additions & 0 deletions lib/esplanade/request/body.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module Esplanade
class Request
class Body < Hash
private_class_method :new

def self.craft(env)
params_string = env['rack.input'].read
params_hash = {}
params_hash = MultiJson.load(params_string) unless params_string == ''
new.merge(params_hash)
end
end
end
end
19 changes: 19 additions & 0 deletions lib/esplanade/request/error.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
module Esplanade
class Request
class Error
def self.unsuitable(message)
status = '400'
headers = { 'Content-Type' => 'application/json; charset=utf-8' }
body = [MultiJson.dump(error: [message[2..-3]])]
[status, headers, body]
end

def self.not_documented
status = '400'
headers = { 'Content-Type' => 'application/json; charset=utf-8' }
body = [MultiJson.dump(error: ['Not documented'])]
[status, headers, body]
end
end
end
end
Loading

0 comments on commit 3f6d5b8

Please sign in to comment.