我可以拥有依赖于值的自定义 Sequelize 验证器吗?

Sha*_*oon 4 validation node.js sequelize.js

在我的模型中,我有

  level: {
    type: DataTypes.ENUM('state', 'service-area'),
    allowNull: false,
    validate: {
      isIn: {
        args: [
          ['state', 'service-area']
        ],
        msg: 'level should be one of state,service-area'
      }
    }
  },
      assignedStates: {
        type: DataTypes.ARRAY(DataTypes.STRING),
        allowNull: true
      },
      assignedServiceAreas: {
        type: DataTypes.ARRAY(DataTypes.STRING),
        allowNull: true
      },
Run Code Online (Sandbox Code Playgroud)

我想,如果要添加一个校验levelstate那么assignedStates不应该是零。我该怎么做?

Ant*_*ich 6

您可以使用模型验证来做到这一点。第三个参数允许您验证整个模型:

const Levels = {
  State: 'state',
  ServiceArea: 'service-area'
}

const Location = sequelize.define(
  "location", {
    level: {
      type: DataTypes.ENUM(...Object.values(Levels)),
      allowNull: false,
      validate: {
        isIn: {
          args: [Object.values(Levels)],
          msg: "level should be one of state,service-area"
        }
      }
    },
    assignedStates: {
      type: DataTypes.ARRAY(DataTypes.STRING),
      allowNull: true
    },
    assignedServiceAreas: {
      type: DataTypes.ARRAY(DataTypes.STRING),
      allowNull: true
    }
  }, {
    validate: {
      assignedValuesNotNul() {
        // Here "this" is a refference to the whole object.
        // So you can apply any validation logic.
        if (this.level === Levels.State && !this.assignedStates) {
          throw new Error(
            'assignedStates should not be null when level is "state"'
          );
        }

        if (this.level === Levels.ServiceArea && !this.assignedServiceAreas) {
          throw new Error(
            'assignedSerivceAreas should not be null when level is "service-areas"'
          );
        }
      }
    }
  }
);
Run Code Online (Sandbox Code Playgroud)