Skip to content

Commit

Permalink
Merge pull request #9 from pdanpdan/patch-1
Browse files Browse the repository at this point in the history
feat: Implement array parsing, enum skipping if invalid
  • Loading branch information
thedumbterminal authored Dec 3, 2018
2 parents 68a1e20 + 96ae919 commit 3417004
Showing 1 changed file with 31 additions and 4 deletions.
35 changes: 31 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ const typeMapping = {
'number': 'float'
}

const reSymbol = /^[A-Za-z_][A-Za-z0-9_]*$/;

jsonSchemaAvro.convert = (jsonSchema) => {
if(!jsonSchema){
throw new Error('No schema given')
Expand All @@ -30,6 +32,10 @@ jsonSchemaAvro._isComplex = (schema) => {
return schema.type === 'object'
}

jsonSchemaAvro._isArray = (schema) => {
return schema.type === 'array'
}

jsonSchemaAvro._hasEnum = (schema) => {
return Boolean(schema.enum)
}
Expand All @@ -39,6 +45,9 @@ jsonSchemaAvro._convertProperties = (schema) => {
if(jsonSchemaAvro._isComplex(schema[item])){
return jsonSchemaAvro._convertComplexProperty(item, schema[item])
}
else if (jsonSchemaAvro._isArray(schema[item])) {
return jsonSchemaAvro._convertArrayProperty(item, schema[item])
}
else if(jsonSchemaAvro._hasEnum(schema[item])){
return jsonSchemaAvro._convertEnumProperty(item, schema[item])
}
Expand All @@ -54,19 +63,37 @@ jsonSchemaAvro._convertComplexProperty = (name, contents) => {
type: 'record',
name: `${name}_record`,
fields: jsonSchemaAvro._convertProperties(contents.properties || {})
}
}
}
}

jsonSchemaAvro._convertArrayProperty = (name, contents) => {
return {
name: name,
doc: contents.description || '',
type: {
type: 'array',
items: jsonSchemaAvro._isComplex(contents.items)
? {
type: 'record',
name: `${name}_record`,
fields: jsonSchemaAvro._convertProperties(contents.items.properties || {})
}
: jsonSchemaAvro._convertProperty(name, contents.items)
}
}
}

jsonSchemaAvro._convertEnumProperty = (name, contents) => {
const valid = contents.enum.every((symbol) => reSymbol.test(symbol))
let prop = {
name: name,
doc: contents.description || '',
type: {
type: valid ? {
type: 'enum',
name: `${name}_enum`,
symbols: contents.enum
}
} : 'string'
}
if(contents.hasOwnProperty('default')){
prop.default = contents.default
Expand All @@ -89,4 +116,4 @@ jsonSchemaAvro._convertProperty = (name, value) => {
prop.type = typeMapping[value.type]
}
return prop
}
}

0 comments on commit 3417004

Please sign in to comment.