A Sequelize column that cannot be updated

2019-06-16 16:27发布

Is it possible to create a column on a MySQL table using Sequelize that can be initialized when creating a new row, but never updated?

For example, a REST service allows a user to update his profile. He can change any field except his id. I can strip the id from the request on the API route, but that's a little redundant because there are a number of different models that behave similarly. Ideally, I'd like to be able to define a constraint in Sequelize that prevents the id column from being set to anything other than DEFAULT.

Currently, I'm using a setterMethod for the id to manually throw a ValidationError, but this seems hackish, so I was wondering if there's a cleaner way of doing this. Even worse is that this implementation still allows the id to be set when creating a new record, but I don't know a way around this as when Sequelize generates the query it calls setterMethods.id to set the value to DEFAULT.

return sequelize.define('Foo',
    {
        title: {
            type: DataTypes.STRING,
            allowNull: false,
            unique: true,
            validate: {
                notEmpty: true
            }
        }
    },
    {
        setterMethods: {
            id: function (value) {
                if (!this.isNewRecord) {
                    throw new sequelize.ValidationError(null, [
                        new sequelize.ValidationErrorItem('readonly', 'id may not be set', 'id', value)
                    ]);
                }
            }
        }
    }
);

1条回答
仙女界的扛把子
2楼-- · 2019-06-16 16:46

Look at this Sequelize plugin:

https://www.npmjs.com/package/sequelize-noupdate-attributes

It adds support for no update and read-only attributes in Sequelize models.

In your specific case, you could configure the attribute with the following flags:

{
  title: {
    type: DataTypes.STRING,
    allowNull: false,
    unique   : true,
    noUpdate : true
  }
}

That will allow the initial set of the title attribute if is null, and then prevent any further modifications once is already set.

Disclaimer: I'm the plugin author.

查看更多
登录 后发表回答