A Sequelize column that cannot be updated

假如想象 提交于 2019-12-22 04:12:08

问题


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:


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.



来源:https://stackoverflow.com/questions/29499051/a-sequelize-column-that-cannot-be-updated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!