Sha256: ea5d7551526196ccc1bcde127c15e9e51dd0345e252f5b85cbcf17983e921633

Contents?: true

Size: 1.88 KB

Versions: 3

Compression:

Stored size: 1.88 KB

Contents

require 'uri'
require 'rack/request'

module Useless
  module Doc
    module Rack

      # +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
      # 404. If the requested subdomain is not in the list of supported
      # subdomains specified at initialization, the proxy will also respond
      # with a 404.
      #
      class Proxy

        def initialize(subdomains)
          @subdomains = subdomains
        end

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

        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

        private

        def valid_subdomain?(url)
          @subdomains.include?(url[/((?:\w|\-)+)\.doc\./, 1])
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
useless-doc-0.2.3 lib/useless/doc/rack/proxy.rb
useless-doc-0.2.2 lib/useless/doc/rack/proxy.rb
useless-doc-0.2.1 lib/useless/doc/rack/proxy.rb