avro-schema-validator
Version:
A tool to infer AVRO schema's from JSON messages, and to validate it.
76 lines • 3.19 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var fs = require("fs");
var path = require("path");
var avsc_1 = require("avsc");
var parser = require("xml2json");
var Parser = (function () {
function Parser(option) {
this.option = option;
this.json = this.loadFile(option.file);
if (option.schema) {
this.schemaType = avsc_1.Type.forSchema(this.loadJSON(option.schema), {
wrapUnions: option.wrapped ? true : 'auto'
});
}
else {
this.schemaFile =
option.output ||
option.file.replace(path.extname(option.file), '.avsc');
}
}
Parser.prototype.run = function () {
if (this.schemaType) {
var isValid = this.validateJSON(this.json, this.schemaType);
console.log("The message is " + (isValid ? '' : 'in') + "valid.");
}
else {
this.inferSchema(this.json, this.schemaFile);
}
};
Parser.prototype.validateJSON = function (json, schemaType, optErrorHook) {
if (json === void 0) { json = this.json; }
if (schemaType === void 0) { schemaType = this.schemaType; }
var errorHook = optErrorHook ? optErrorHook : function (path, part) {
return console.error('\x1b[1;31m%s\x1b[0m', "Validation error: path " + path.join(', ') + ", part " + JSON.stringify(part, null, 2));
};
var isValid = schemaType.isValid(json, { errorHook: errorHook });
if (!isValid && typeof this.option.wrapped === 'undefined') {
console.info('The message is invalid when using \'auto\' wrap mode. Retrying using wrapped mode (-w option).');
var newParser = new Parser(Object.assign(this.option, { wrapped: true }));
return newParser.validateJSON();
}
return isValid;
};
Parser.prototype.inferSchema = function (json, schemaFile) {
var type = avsc_1.Type.forValue(json);
schemaFile = path.resolve(process.cwd(), schemaFile);
fs.writeFileSync(schemaFile, JSON.stringify(type.schema(), null, 2));
console.info("Schema file written to " + schemaFile + ".");
};
Parser.prototype.loadFile = function (filename) {
var ext = path.extname(filename).toLowerCase();
switch (ext) {
case '.json':
case '.geojson':
case '.avsc':
return this.loadJSON(filename);
case '.xml':
return this.loadXML(filename);
default:
console.error("Unknown file type: " + ext + ".");
}
};
Parser.prototype.loadJSON = function (filename) {
return JSON.parse(fs.readFileSync(path.resolve(process.cwd(), filename), 'utf8'));
};
Parser.prototype.loadXML = function (filename) {
return parser.toJson(fs.readFileSync(path.resolve(process.cwd(), filename), 'utf8'), {
object: true,
coerce: true
});
};
return Parser;
}());
exports.Parser = Parser;
//# sourceMappingURL=parser.js.map