Class: Natsuzora::Contract::Document

Inherits:
Object
  • Object
show all
Defined in:
lib/natsuzora/contract/document.rb

Overview

Parsed contract document with type definitions and root fields.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(types: {}, fields: {}) ⇒ Document

Returns a new instance of Document.



15
16
17
18
# File 'lib/natsuzora/contract/document.rb', line 15

def initialize(types: {}, fields: {})
  @types = types   # Hash<String, TypeDef>
  @fields = fields # Hash<String, Field>
end

Instance Attribute Details

#fieldsObject (readonly)

Returns the value of attribute fields.



13
14
15
# File 'lib/natsuzora/contract/document.rb', line 13

def fields
  @fields
end

#typesObject (readonly)

Returns the value of attribute types.



13
14
15
# File 'lib/natsuzora/contract/document.rb', line 13

def types
  @types
end

Instance Method Details

#to_contract(target = ValidationTarget::CURRENT) ⇒ Object

Build the resolved root AST::Record for the specified target.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/natsuzora/contract/document.rb', line 21

def to_contract(target = ValidationTarget::CURRENT)
  resolver = TypeRefResolver.new(
    @types,
    target: target,
    on_missing: ->(name) { raise ParseError.new("undefined type '#{name}'", 0, 0) },
    on_unavailable: ->(_) { AST::Any.new },
    on_cyclic: ->(name) { raise ParseError.new("cyclic type reference '#{name}'", 0, 0) }
  )

  properties = {}
  required = []

  @fields.each do |name, field|
    contract = field.for_target(target)
    next unless contract

    properties[name] = resolver.resolve(contract)
    required << name
  end

  AST::Record.new(properties, required)
end