Sequelize column that cannot be updated

Is it possible to create a column in a MySQL table using Sequelize, which can be initialized when a new row is created but not updated?

For example, the REST service allows a user to update their profile. He can change any field except his id . I can remove the id from the request on the API route, but this is a bit redundant because there are several different models that behave the same. Ideally, I would like to define a constraint in Sequelize that prevents the id column from being set to a value other than DEFAULT .

I am currently using setterMethod for id to manually throw a ValidationError , but this seems like a hacker, so I was wondering if there is a cleaner way to do this. The worst part is that this implementation still allows you to set the id when creating a new record, but I don’t know how this happens when Sequelize generates a query that it calls setterMethods.id to set the DEFAULT value.

 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) ]); } } } } ); 
+6
source share
1 answer

Take a look at this Sequelize plugin:

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

It adds support without update and read attributes only on Sequelize models.

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

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

This will allow the source set of the title attribute if it is null, and then prevent any additional changes that are already set.

Disclaimer: I am the author of the plugin.

+3
source

Source: https://habr.com/ru/post/984810/


All Articles