我想为具有以下格式的文档制作SimpleSchema:
{
...,
permissions: {
foo: {allow: ["user1", "user2"]},
bar: {allow: ["admin"]},
}
}
如果foo
和bar
是架构中众所周知的字符串,我会这样做:
const PermissionsSchema = new SimpleSchema({
allow: {type: [String]},
});
new SimpleSchema({
...,
'permissions.foo': {
type: PermissionSchema,
},
'permissions.bar': {
type: PermissionSchema,
},
})
但是,在这种情况下,可以有任意字符串键,而不仅仅是foo
和bar
。值必须始终与PermissionsSchema
匹配。有没有办法表达这个?
答案 0 :(得分:0)
import { ValidationError } from 'mdg:validation-error';
function permissionsValidator(keyRegEx) {
if (!(keyRegEx instanceof RegExp)) {
throw new Error('must pass a regular expression');
}
return function() {
// https://github.com/aldeed/meteor-simple-schema#custom-validation
const value = this.value;
for (let key in value) {
if (value.hasOwnProperty(key)) {
if (!keyRegEx.test(key)) {
return 'regEx';
}
try {
PermissionSchema.validate(value[key]);
} catch (ex) {
if (ex instanceof ValidationError) {
return ex.error;
}
}
}
}
};
}
new SimpleSchema({
...,
permissions: {
type: Object,
custom: permissionsValidator(/^.*$/),
blackbox: true,
optional: true,
defaultValue: {},
},
});
但出现的错误消息是垃圾。改进或更好的策略仍然受到欢迎。