Code Monkey home page Code Monkey logo

wor-requests's Introduction

Wolox on Rails - Requests

Gem Version Build Status Code Climate

Make external requests in you service objects, with easy logging and error handling!

Installation

Add this line to your application's Gemfile:

gem 'wor-requests'

And then execute:

$ bundle

Or install it yourself as:

$ gem install wor-requests

Then you can run rails generate wor:requests:install to create the initializer:

# config/initializers/wor_requests.rb

Wor::Requests.configure do |config|
  config.logger = Rails.logger
end

Generators

rails generate wor:requests:service NAME

Generator options

module

Specifying the module name as:

rails generate wor:requests:service NAME --module MODULE_NAME

We can create a service with an inner class called NAME, and external module called MODULE_NAME

module ModuleName
  class NameService < Wor::Requests::Base
    # Your code here
  end
end

Service example

To write your first Service using Wor-requests you can write something like this:

require 'wor/requests'

class GithubService < Wor::Requests::Base
  def repositories(username)
    get(
      attempting_to: "get repositories of #{username}",
      path: "/users/#{username}/repos"
    )
  rescue Wor::Requests::RequestError => e
    puts e.message
  end

  protected

  def base_url
    'https://api.github.com'
  end
end

puts GithubService.new.repositories('wolox')

If you need to get the response headers, add a block in the call with the headers output

GithubService.new.repositories('wolox') do |response|
  puts response.headers
end

If you need to send body parameters in a post request you can write something like this:

require 'wor/requests'

class ExternalService < Wor::Requests::Base
  def post_request_example(authorization)
    post(
      attempting_to: 'Make a POST request to an external service.',
      path: '/some_endpoint',
      headers: {
        Authorization: authorization,
        'Content-type' => 'application/json'
      },
      body: {
        # Some Json
      }
    )
  end

  protected

  def base_url
    'https://external.service.com'
  end
end

ExternalService.new.post_request_example(token)

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Run rubocop lint (rubocop -R --format simple)
  5. Run rspec tests (bundle exec rspec)
  6. Push your branch (git push origin my-new-feature)
  7. Create a new Pull Request

About

This project was developed by Diego Raffo along with Michel Agopian and it was written by Wolox.

Maintainers: Samir Tapiero

Contributors: Diego Raffo Michel Agopian

Wolox

License

wor-requests is available under the MIT license.

Copyright (c) 2017 Wolox

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.

wor-requests's People

Contributors

alebian avatar blacksam07 avatar eegc-wolox avatar gussiciliano avatar hdf1996 avatar leamotta avatar mishuagopian avatar mtejedorwolox avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wor-requests's Issues

Error with empty bodys

Whenever you receive an empty body as a response, the json parser fails to decode the response.

Will be useful to be able to select different parsers for different services. For example json parser, xml parser, raw_parser (doesn't parse at all)

Add an example of how to access the headers of the responses

Currently we need to do something like this to access the headers instead of the eample in the readme

require 'wor-requests'
require 'pry'

class GithubService < Wor::Requests::Base
  def repositories(username, &block)
    get(
      attempting_to: "get repositories of #{username}",
      path: "/users/#{username}/repos", &block)
  rescue Wor::Requests::RequestError => e
    puts e.message
  end

  private

  def base_url
    'https://api.github.com'
  end
end

GithubService.new.repositories('alebian') do |r|
  puts response.headers
end

Would be great to have this in some place in the readme or in a wiki :P

Logs appear during RSPEC

The request logs appear during the rspec run.
The requests are stubbed to return specific response with webmock

▶ rspec .

Randomized with seed 46047
[rspec-sidekiq] WARNING! Sidekiq will *NOT* process jobs in this environment. See https://github.com/philostler/rspec-sidekiq/wiki/FAQ-&-Troubleshooting
...................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................I, [2017-12-29T11:58:17.632939 #5087]  INFO -- : ATTEMPTING TO: get admin token
E, [2017-12-29T11:58:17.635055 #5087] ERROR -- : ERROR when trying to get admin token. Got status code: 500. 
.I, [2017-12-29T11:58:17.670625 #5087]  INFO -- : ATTEMPTING TO: get admin token
I, [2017-12-29T11:58:17.672560 #5087]  INFO -- : SUCCESS: get admin token
I, [2017-12-29T11:58:17.673180 #5087]  INFO -- : ATTEMPTING TO: register vehicle 556
E, [2017-12-29T11:58:17.674881 #5087] ERROR -- : ERROR when trying to register vehicle 556. Got status code: 500. 
.I, [2017-12-29T11:58:17.704330 #5087]  INFO -- : ATTEMPTING TO: get admin token
I, [2017-12-29T11:58:17.706026 #5087]  INFO -- : SUCCESS: get admin token
I, [2017-12-29T11:58:17.706157 #5087]  INFO -- : ATTEMPTING TO: register vehicle 557
I, [2017-12-29T11:58:17.707024 #5087]  INFO -- : SUCCESS: register vehicle 557
.I, [2017-12-29T11:58:17.744163 #5087]  INFO -- : ATTEMPTING TO: get admin token
I, [2017-12-29T11:58:17.745895 #5087]  INFO -- : SUCCESS: get admin token
I, [2017-12-29T11:58:17.746018 #5087]  INFO -- : ATTEMPTING TO: register vehicle 558
I, [2017-12-29T11:58:17.746900 #5087]  INFO -- : SUCCESS: register vehicle 558
.I, [2017-12-29T11:58:17.781548 #5087]  INFO -- : ATTEMPTING TO: get admin token
I, [2017-12-29T11:58:17.783540 #5087]  INFO -- : SUCCESS: get admin token
I, [2017-12-29T11:58:17.783714 #5087]  INFO -- : ATTEMPTING TO: register vehicle 559
I, [2017-12-29T11:58:17.784725 #5087]  INFO -- : SUCCESS: register vehicle 559
.I, [2017-12-29T11:58:17.822138 #5087]  INFO -- : ATTEMPTING TO: get admin token
I, [2017-12-29T11:58:17.823979 #5087]  INFO -- : SUCCESS: get admin token
I, [2017-12-29T11:58:17.824119 #5087]  INFO -- : ATTEMPTING TO: register vehicle 560
I, [2017-12-29T11:58:17.825087 #5087]  INFO -- : SUCCESS: register vehicle 560
.........................................................................................................................................................................................................................................................................................................................................................................................................................................

Add error when base_url is empty

When the base_url method is defined, but the string is not defined (it has an empty string) it returns this error:

undefined method []' for nil:NilClass`

It should return a more descriptive error message.

HTTParty issue with body containing array of jsons.

We should be aware that if you want to make a post request with HTTParty with a body like the following:

{ 
  values: [{some_attr: some_value1, another_attr: another_value1},
           {some_attr: some_value2, another_attr: another_value2},
           {some_attr: some_value3, another_attr: another_value3}]
}

HTTParty transforms it in the following:

{
  values: [{some_attr: [some_value1, some_value1, some_value1]}, 
           {another_attr: [another_value1, another_value2, another_value3]}]
}

There is a possible fix here:
https://stackoverflow.com/questions/21856373/sending-array-variables-using-httparty

Body must be a JSON

Summary

if we send an array in the body, the resulting body is translated to
{ dody: array_param[]=value1, array_param[]=value2, .... etc }

It shoud be converted to_json manualy before it gets to httparty

Raise exception when sending body in GET and DELETE

According to the RFC, GET and DELETE methods do not receive a body. The gem simply ignores if the user sends a body in the request, I think it should raise an error when this happens, because it will save the user time debugging

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.