UNPKG

nowjs-core

Version:

NowCanDo Javascript Core [nowjs-core] is a library written by TypeScript code maintains under Apache 2.0 licence

36 lines (35 loc) 1.35 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const index_1 = require("../index"); exports.VALIDATOR_JSON_METADATA_KEY = Symbol('validation:validator:isJson'); function isJson(errorMessage) { return (target, propertyKey, descriptor) => { const original = descriptor.value; Reflect.defineMetadata(exports.VALIDATOR_JSON_METADATA_KEY, null, target, propertyKey); Reflect.defineMetadata(index_1.VALIDATOR_METADATA_KEY, new JsonValidator(errorMessage), target, propertyKey); }; } exports.isJson = isJson; class JsonValidator extends index_1.ValidatorBase { constructor(errorMessage = 'The value of ${DisplayName} must have valu type: ${ValueType} .') { super('Json', errorMessage); } isMatch(value) { try { return JSON.parse(value) !== null; } catch (error) { return false; } } validate(context) { if (context.Value === undefined || context.Value === null) { return Promise.resolve(true); } if (!this.isMatch(context.Value)) { return Promise.reject(new index_1.ValidatorException(this.Name, context.Target, context.PropertyName, this.formatErrorMessage(context))); } return Promise.resolve(true); } } exports.JsonValidator = JsonValidator;