diff --git a/src/index.js b/src/index.js index b66034d..f95679d 100644 --- a/src/index.js +++ b/src/index.js @@ -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') @@ -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) } @@ -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]) } @@ -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 @@ -89,4 +116,4 @@ jsonSchemaAvro._convertProperty = (name, value) => { prop.type = typeMapping[value.type] } return prop -} \ No newline at end of file +}