Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
ursm committed Jul 6, 2024
0 parents commit b1796ad
Show file tree
Hide file tree
Showing 20 changed files with 480 additions and 0 deletions.
25 changes: 25 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: Test

on:
push:

jobs:
build:
runs-on: ubuntu-latest

strategy:
matrix:
ruby:
- 3.1.6
- 3.2.4
- 3.3.3

steps:
- uses: actions/checkout@v4

- uses: ruby/setup-ruby@v1
with:
ruby-version: ${{ matrix.ruby }}
bundler-cache: true

- run: bundle exec rake
11 changes: 11 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/.bundle/
/.yardoc
/_yardoc/
/coverage/
/doc/
/pkg/
/spec/reports/
/tmp/

# rspec failure tracking
.rspec_status
3 changes: 3 additions & 0 deletions .rspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
--format documentation
--color
--require spec_helper
7 changes: 7 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
source 'https://rubygems.org'

gemspec

gem 'rake'
gem 'rspec'
gem 'webmock'
60 changes: 60 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
PATH
remote: .
specs:
fetch-api (0.1.0)
net-http
rack
singleton
uri

GEM
remote: https://rubygems.org/
specs:
addressable (2.8.7)
public_suffix (>= 2.0.2, < 7.0)
bigdecimal (3.1.8)
crack (1.0.0)
bigdecimal
rexml
diff-lcs (1.5.1)
hashdiff (1.1.0)
net-http (0.4.1)
uri
public_suffix (6.0.0)
rack (3.1.6)
rake (13.2.1)
rexml (3.3.1)
strscan
rspec (3.13.0)
rspec-core (~> 3.13.0)
rspec-expectations (~> 3.13.0)
rspec-mocks (~> 3.13.0)
rspec-core (3.13.0)
rspec-support (~> 3.13.0)
rspec-expectations (3.13.1)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.13.0)
rspec-mocks (3.13.1)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.13.0)
rspec-support (3.13.1)
singleton (0.2.0)
strscan (3.1.0)
uri (0.13.0)
webmock (3.23.1)
addressable (>= 2.8.0)
crack (>= 0.3.2)
hashdiff (>= 0.4.0, < 2.0.0)

PLATFORMS
ruby
x86_64-linux

DEPENDENCIES
fetch-api!
rake
rspec
webmock

BUNDLED WITH
2.5.14
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) 2024 Keita Urashima

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.
90 changes: 90 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# Fetch API

Ruby's Net::HTTP is very powerful, but has a complicated API. OpenURI is easy to use, but has limited functionality. Third-party HTTP clients each have different APIs, and it can sometimes be difficult to learn how to use them.

There is one HTTP client that we can all use. It is the browser's Fetch API. This is an HTTP client for Ruby that can be used in a way that is similar to the Fetch API.

This is not intended to be a complete copy of the Fetch API. For example, responses are returned synchronously rather than asynchronously, as that is more familiar behavior for Ruby programmers. It is only "like" the Fetch API.

## Installation

Install the gem and add to the application's Gemfile by executing:

```
$ bundle add fetch-api
```

If bundler is not being used to manage dependencies, install the gem by executing:

```
$ gem install fetch-api
```

## Usage

### Basic

``` ruby
require 'fetch-api'

res = Fetch::API.fetch('https://example.com')

# res is a Rack::Response object
puts res.body
```

``` ruby
require 'fetch-api'

include Fetch::API

res = fetch('https://example.com')
```

### Post JSON

``` ruby
res = fetch('http://example.com', **{
method: 'POST',

headers: {
'Content-Type' => 'application/json'
},

body: {
name: 'Alice'
}.to_json
})
```

### Post Form

``` ruby
res = fetch('http://example.com', **{
method: 'POST',

headers: {
'Content-Type' => 'multipart/form-data'
},

body: Rack::Multipart.build_multipart(
file: Rack::Multipart::UploadedFile.new(io: StringIO.new('foo'), filename: 'foo.txt')
)
})
```

Note: `Rack::Multipart.build_multipart` returns nil if the parameter does not include UploadedFile.

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/ursm/fetch-api.

## License

The gem is available as open source under the terms of the [MIT License](https://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
9 changes: 9 additions & 0 deletions bin/console
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/usr/bin/env ruby
require 'bundler/setup'
require 'fetch'

# 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.

require 'irb'
IRB.start(__FILE__)
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
32 changes: 32 additions & 0 deletions fetch-api.gemspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
require_relative 'lib/fetch/version'

Gem::Specification.new do |spec|
spec.name = 'fetch-api'
spec.version = Fetch::VERSION
spec.authors = ['Keita Urashima']
spec.email = ['ursm@ursm.jp']

spec.summary = 'Something like the Fetch API for Ruby'
spec.homepage = 'https://github.com/ursm/fetch-api'
spec.license = 'MIT'
spec.required_ruby_version = '>= 3.1.0'

spec.metadata['homepage_uri'] = spec.homepage
spec.metadata['source_code_uri'] = 'https://github.com/ursm/fetch-api.git'

spec.files = Dir[
'LICENSE.txt',
'README.md',
'lib/**/*.rb',
'sig/**/*.rbs',
]

spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{\Aexe/}) { File.basename(_1) }
spec.require_paths = ['lib']

spec.add_dependency 'net-http'
spec.add_dependency 'rack'
spec.add_dependency 'singleton'
spec.add_dependency 'uri'
end
1 change: 1 addition & 0 deletions lib/fetch-api.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
require_relative 'fetch/api'
7 changes: 7 additions & 0 deletions lib/fetch.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
require_relative 'fetch/version'
require_relative 'fetch/api'

module Fetch
class Error < StandardError; end
class RedirectError < Error; end
end
11 changes: 11 additions & 0 deletions lib/fetch/api.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
require_relative 'client'

module Fetch
module API
module_function

def fetch(...)
Client.instance.fetch(...)
end
end
end
51 changes: 51 additions & 0 deletions lib/fetch/client.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
require_relative '../fetch'

require 'net/http'
require 'net/https'
require 'rack/response'
require 'singleton'
require 'uri'

module Fetch
class Client
include Singleton

def fetch(resource, method: 'GET', headers: {}, body: nil, redirect: 'follow')
uri = URI.parse(resource)
req = Net::HTTP.const_get(method.capitalize).new(uri)

headers.each do |k, v|
req[k] = v
end

req.body = body

http = Net::HTTP.new(uri.hostname, uri.port)
http.use_ssl = uri.scheme == 'https'

res = http.start { _1.request(req) }

case res
when Net::HTTPRedirection
case redirect
when 'follow'
fetch(res['location'], method:, headers:, body:, redirect:)
when 'error'
raise RedirectError, "redirected to #{res['location']}"
when 'manual'
to_rack_response(res)
else
raise ArgumentError, "invalid redirect option: #{redirect}"
end
else
to_rack_response(res)
end
end

private

def to_rack_response(res)
Rack::Response.new(res.body, res.code, res.to_hash)
end
end
end
3 changes: 3 additions & 0 deletions lib/fetch/version.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module Fetch
VERSION = '0.1.0'
end
4 changes: 4 additions & 0 deletions sig/fetch.rbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module Fetch
VERSION: String
# See the writing guide of rbs: https://github.com/ruby/rbs#guides
end
Loading

0 comments on commit b1796ad

Please sign in to comment.