easy-schema-validator
Version:
Easily validate JSON Schema.
46 lines • 1.94 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const Ajv = require("ajv");
const cross_fetch_1 = require("cross-fetch");
function defaultResolver(uri) {
return __awaiter(this, void 0, void 0, function* () {
const res = yield cross_fetch_1.default(uri);
const json = yield res.json();
return json;
});
}
class SchemaValidator {
constructor(schema, options = {}) {
this.schema = schema;
this.ajv = new Ajv({
useDefaults: options.useDefaults !== false,
loadSchema: defaultResolver,
});
}
validate(data) {
return __awaiter(this, void 0, void 0, function* () {
if (this.validateFunc === undefined) {
this.validateFunc = yield this.ajv.compileAsync(this.schema);
}
yield this.validateFunc(data);
return this.validateFunc.errors || [];
});
}
static validate(data, schema, options = {}) {
return __awaiter(this, void 0, void 0, function* () {
const validator = new SchemaValidator(schema, options);
return validator.validate(data);
});
}
}
exports.default = SchemaValidator;
//# sourceMappingURL=index.js.map