Sha256: ea6d64327ec9914c785b36fe0e40f61edd5702262a97f2a42779f2f5f584b02d

Contents?: true

Size: 1.84 KB

Versions: 12

Compression:

Stored size: 1.84 KB

Contents

module Jdoc
  class Schema
    DEFAULT_ENDPOINT = "https://api.example.com"

    # @param schema [Hash] JSON Schema
    def initialize(schema)
      @json_schema = JsonSchema.parse!(schema).tap(&:expand_references!)
    end

    # @return [Array<Jdoc::Resource>] All top-level properties in its title order
    def resources
      @resources ||= @json_schema.properties.map do |key, property|
        Resource.new(property)
      end.sort
    end

    # @return [String, nil] Title property of this schema
    # @example
    #   schema.title #=> "app"
    def title
      @json_schema.title
    end

    # @return [String, nil] Description property of this schema
    # @example
    #   schema.description #=> "A schema for a small example API."
    def description
      if @json_schema.description
        "#{@json_schema.description}\n\n"
      end
    end

    # @return [String]
    # @example
    #   host_with_port #=> "api.example.com"
    #   host_with_port #=> "api.example.com:3000"
    def host_with_port
      if [80, 443].include?(port)
        host
      else
        "#{host}:#{port}"
      end
    end

    private

    # @return [Fixnum] Port number for this API endpoint
    def port
      root_uri.port || 80
    end

    # @return [String] Host name of API, used at dummy Host header
    # @example
    #   schema.host #=> "api.example.com"
    def host
      root_uri.host
    end

    # @return [URI::Generic] Root endpoint for the API
    # @example
    #   root_uri #=> "https://api.example.com"
    def root_uri
      @root_endpoint = begin
        if link = link_for_root_endpoint
          URI(link.href)
        else
          URI(DEFAULT_ENDPOINT)
        end
      end
    end

    # @return [JsonSchema::Schema::Link]
    def link_for_root_endpoint
      @json_schema.links.find do |link|
        link.rel == "self" && link.href
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
jdoc-0.4.4 lib/jdoc/schema.rb
jdoc-0.4.3 lib/jdoc/schema.rb
jdoc-0.4.2 lib/jdoc/schema.rb
jdoc-0.4.1 lib/jdoc/schema.rb
jdoc-0.4.0 lib/jdoc/schema.rb
jdoc-0.3.4 lib/jdoc/schema.rb
jdoc-0.3.3 lib/jdoc/schema.rb
jdoc-0.3.2 lib/jdoc/schema.rb
jdoc-0.3.1 lib/jdoc/schema.rb
jdoc-0.3.0 lib/jdoc/schema.rb
jdoc-0.2.1 lib/jdoc/schema.rb
jdoc-0.2.0 lib/jdoc/schema.rb