UNPKG

@bitblit/ratchet-misc

Version:

Ratchet miscellaneous tooling that requires smallish dependant libraries

54 lines 2.26 kB
import Validator from 'swagger-model-validator'; import yaml from 'js-yaml'; import { Logger } from '@bitblit/ratchet-common/logger/logger'; import { ErrorRatchet } from '@bitblit/ratchet-common/lang/error-ratchet'; import { MapRatchet } from '@bitblit/ratchet-common/lang/map-ratchet'; export class ModelValidator { allModels; constructor(allModels) { this.allModels = allModels; if (!allModels || Object.keys(allModels).length == 0) { ErrorRatchet.throwFormattedErr('Cannot create model validator, passed models was null/empty : %j', allModels); } } static createFromYamlString(yamlString, rootPath) { const src = yaml.load(yamlString); const modelSrc = rootPath && rootPath.length > 0 ? MapRatchet.findValue(src, rootPath) : src; return ModelValidator.createFromParsedObject(modelSrc); } static createFromParsedObject(parsedObject) { return new ModelValidator(parsedObject); } get modelNames() { return Object.keys(this.allModels); } addModel(modelName, model) { this.allModels[modelName] = model; } fetchModel(modelName) { return this.allModels[modelName]; } validate(modelName, modelObject, emptyAllowed = false, extraPropertiesAllowed = true) { let rval = []; Logger.silly('Validating model %s all definitions are : %j', modelName, this.allModels); const modelEmpty = !modelObject || Object.keys(modelObject).length === 0; if (modelEmpty) { if (!emptyAllowed) { rval.push('Empty / null object sent, but empty not allowed here'); } } else { if (this.allModels && modelName && this.allModels[modelName]) { const validation = new Validator().validate(modelObject, this.allModels[modelName], this.allModels, emptyAllowed, extraPropertiesAllowed); if (validation.errorCount > 0) { rval = validation.errors.map((e) => e.message); } } else { rval = ['Model named "' + modelName + '" not present in schema']; } } return rval; } } //# sourceMappingURL=model-validator.js.map