我做了一个结构比较函数来处理这样的情况,分享给大家,希望对大家有所启发和帮助:
假设您使用的是sails v1
在./api/services 中创建一个名为ModelService.js 的文件,代码如下:
module.exports = {
invalidStructure(schema, input) {
try {
if (schema.type === 'array') {
// Invalid: if input is not array
// OR some of input[items] doesn't match schema.item
return !_.isArray(input) ||
_.some(input, item => this.invalidStructure(schema.item, item));
}
else if (schema.type === 'object') {
// Invalid if input is not an object
// OR if input.keys doesn't match schema.struct.keys
// OR if typeof input[key] doesn't match schema.struct[key]
return !_.isObjectLike(input) ||
!_.isEqual(_.keys(schema.struct), _.keys(input)) ||
_.some(_.keys(input), key => this.invalidStructure(schema.struct[key], input[key]));
}
else { // verifying field value vs schema.type
// TODO: Add other field validations here (i.e. isEmail, required,...etc.)
return typeof input !== schema.type;
}
}
catch (err) {
sails.log.error('Exception in [invalidStructure] : ', err);
return true;
}
}
}
并在您的模型中像这样使用它:
const address = {
type: 'object',
struct: {
name: { type: 'string' },
location: {
type: 'object',
struct: {
x: { type: 'string' },
y: { type: 'string' },
z: { type: 'string' },
}
}
}
}
module.exports = {
attributes: {
address: {
type: 'json',
custom: value => !ModelService.invalidStructure(address, value)
}
}
}
现在我知道这不处理或情况(即required: false)
但它应该让你去匹配json结构和值类型
注意:这是source file。随意使用,或通过 PR 增强