Class: Useless::Doc::Rack::Proxy

Inherits:
Object
  • Object
show all
Defined in:
lib/useless/doc/rack/proxy.rb

Overview

Doc::Proxy is a Rack app that provides an HTML interface to Useless API documentation. It assumes that each API resource responds to INFO requests with documentation JSON that corresponds to the format specified by Doc::Serialization::Load.

It proxies requests according to a simple convention. For example, a GET request to some-api.doc.useless.io/some/resource will result in an OPTIONS request to some-api.useless.io/some/resource.

If there is no corresponding endpoint, the proxy will respond with a

  1. If the requested subdomain is not in the list of supported

subdomains specified at initialization, the proxy will also respond with a 404.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(subdomains) ⇒ Proxy

Returns a new instance of Proxy.



25
26
27
# File 'lib/useless/doc/rack/proxy.rb', line 25

def initialize(subdomains)
  @subdomains = subdomains
end

Class Method Details

.transform_url(url) ⇒ Object



29
30
31
32
33
# File 'lib/useless/doc/rack/proxy.rb', line 29

def self.transform_url(url)
  uri = URI(url)
  new_host = uri.host.gsub(/\.doc\./, '.')
  "#{uri.scheme}://#{new_host}#{uri.path}"
end

Instance Method Details

#call(env) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/useless/doc/rack/proxy.rb', line 35

def call(env)
  unless env['useless.doc.retriever']
    raise 'No retriever specified.'
  end

  request = ::Rack::Request.new(env)

  if valid_subdomain?(request.url)
    url = Proxy.transform_url(request.url)

    if json = env['useless.doc.retriever'].retrieve(url)
      [200, {'Content-Type' => 'application/json'}, [json]]
    else
      [404, {'Content-Type' => 'text/plain'}, ['Documentation JSON is missing.']]
    end
  else
    [404, {'Content-Type' => 'text/plain'}, ['Unknown subdomain.']]
  end
end