Class: Contentful::Importer::JsonSchemaValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/contentful/importer/json_schema_validator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(configuration) ⇒ JsonSchemaValidator

Returns a new instance of JsonSchemaValidator.



9
10
11
12
# File 'lib/contentful/importer/json_schema_validator.rb', line 9

def initialize(configuration)
  @config = configuration
  @logger = Logger.new(STDOUT)
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



7
8
9
# File 'lib/contentful/importer/json_schema_validator.rb', line 7

def config
  @config
end

#loggerObject (readonly)

Returns the value of attribute logger.



7
8
9
# File 'lib/contentful/importer/json_schema_validator.rb', line 7

def logger
  @logger
end

Instance Method Details

#base_schema_formatObject



46
47
48
# File 'lib/contentful/importer/json_schema_validator.rb', line 46

def base_schema_format
  {'type' => 'object', 'properties' => {}}
end

#convert_type(type) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/contentful/importer/json_schema_validator.rb', line 50

def convert_type(type)
  case type
    when 'Text', 'Date', 'Symbol'
      'string'
    when 'Number'
      'float'
    when 'Asset', 'Entry'
      'object'
    else
      type.downcase
  end
end

#parse_content_type_schema(ct_file) ⇒ Object



37
38
39
40
41
42
43
44
# File 'lib/contentful/importer/json_schema_validator.rb', line 37

def parse_content_type_schema(ct_file)
  new_hash = base_schema_format
  ct_file['fields'].each do |key|
    type = convert_type(key['type'])
    new_hash['properties'].merge!({key['id'] => {'type' => type}})
  end
  new_hash
end

#validate_entry(content_type_filename, schema) ⇒ Object



26
27
28
29
30
31
32
33
34
35
# File 'lib/contentful/importer/json_schema_validator.rb', line 26

def validate_entry(content_type_filename, schema)
  Dir.glob("#{config.entries_dir}/#{content_type_filename}/*") do |entry_file|
    entry_schema = JSON.parse(File.read(entry_file))
    begin
      JSON::Validator.validate!(schema, entry_schema)
    rescue JSON::Schema::ValidationError => error
      logger.info "#{error.message}! Path to invalid entry: #{entry_file}"
    end
  end
end

#validate_schema(content_type_file) ⇒ Object



20
21
22
23
24
# File 'lib/contentful/importer/json_schema_validator.rb', line 20

def validate_schema(content_type_file)
  schema = parse_content_type_schema(JSON.parse(File.read(content_type_file)))
  content_type_filename = File.basename(content_type_file, '.*')
  validate_entry(content_type_filename, schema)
end

#validate_schemasObject



14
15
16
17
18
# File 'lib/contentful/importer/json_schema_validator.rb', line 14

def validate_schemas
  Dir.glob("#{config.collections_dir}/*") do |content_type_file|
    validate_schema(content_type_file)
  end
end