SimpleSchema 可以表达"object with custom keys and specific schema for values"吗?

Can SimpleSchema express "object with custom keys and specific schema for values"?

我想为具有以下格式的文档制作 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。有什么表达方式吗?

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

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