SimpleSchema可以表达“具有自定义键和值的特定架构的对象”吗?

时间:2016-11-24 09:06:28

标签: meteor simple-schema

我想为具有以下格式的文档制作SimpleSchema

{
  ...,
  permissions: {
    foo: {allow: ["user1", "user2"]},
    bar: {allow: ["admin"]},
  }
}

如果foobar是架构中众所周知的字符串,我会这样做:

const PermissionsSchema = new SimpleSchema({
  allow: {type: [String]},
});

new SimpleSchema({
  ...,
  'permissions.foo': {
    type: PermissionSchema,
  },
  'permissions.bar': {
    type: PermissionSchema,
  },
})

但是,在这种情况下,可以有任意字符串键,而不仅仅是foobar。值必须始终与PermissionsSchema匹配。有没有办法表达这个?

1 个答案:

答案 0 :(得分:0)

Custom validators救援!

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: {},
  },
});

但出现的错误消息是垃圾。改进或更好的策略仍然受到欢迎。