obj-valid
Version:
This package can check is your object has correct structure without using typescript. As you know after transpilation interfaces disappear. If you want to check object structure on production or in clean javascript you can use this package.
59 lines • 2.42 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.compare = void 0;
var kind_of_1 = __importDefault(require("kind-of"));
var compare = function (schema, newSchema) {
// function basis taken from https://javascript.plainenglish.io/4-ways-to-compare-objects-in-javascript-97fe9b2a949c
var result = {
score: true,
wrongProperties: [],
};
var notRequirePropertiesProblemResult = {
score: false,
wrongProperties: ['notRequireProperties'],
};
var doesNotRequirePropertiesExist = schema.hasOwnProperty('notRequireProperties');
if (doesNotRequirePropertiesExist) {
if (!Array.isArray(schema.notRequireProperties)) {
return notRequirePropertiesProblemResult;
}
if (schema.notRequireProperties.every(function (element) { return typeof element !== 'string'; })) {
return notRequirePropertiesProblemResult;
}
}
var props1 = Object.getOwnPropertyNames(schema);
var props2 = Object.getOwnPropertyNames(newSchema);
for (var i = 0; i < props1.length; i++) {
var prop = props1[i];
if (prop === 'notRequireProperties')
continue;
if (doesNotRequirePropertiesExist &&
props2.indexOf(prop) === -1 &&
schema.notRequireProperties.indexOf(prop) !== -1) {
continue;
}
if (props1[0] === 'type' &&
props1[1] === 'value' &&
props2[0] === 'type' &&
props2[1] === 'value') {
if (schema.type === 'array' && schema.value === 'any') {
schema.value = newSchema.value;
}
if (newSchema.type === 'array' && newSchema.value === 'any') {
newSchema.value = schema.value;
}
}
var bothAreObjects = kind_of_1.default(schema[prop]) === 'object' && kind_of_1.default(newSchema[prop]) === 'object';
if ((!bothAreObjects && schema[prop] !== newSchema[prop]) ||
(bothAreObjects && !exports.compare(schema[prop], newSchema[prop]).score)) {
result.score = false;
result.wrongProperties.push(prop);
}
}
return result;
};
exports.compare = compare;
//# sourceMappingURL=compare.js.map