Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Sequelize column that cannot be updated

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)
                    ]);
                }
            }
        }
    }
);
like image 702
M Miller Avatar asked Apr 07 '15 18:04

M Miller


People also ask

What does update in Sequelize return?

Update function of sequelize returns a number of affected rows (first parameter of result array).

What is association in Sequelize?

The A.hasMany(B) association means that a One-To-Many relationship exists between A and B , with the foreign key being defined in the target model ( B ). These three calls will cause Sequelize to automatically add foreign keys to the appropriate models (unless they are already present).

What is Sequelize sync()?

The Sequelize instance method sync() is used to synchronize your Sequelize model with your database tables. The synchronization happens at the table level. When your table doesn't exist the sync() method will generate and run a CREATE TABLE statement for you.

How to add foreign key in Sequelize model?

Sequelize association methods also accept an options object that you can use to configure the details of the association. For example, you can change the foreign key name on the table by adding the foreignKey property: User. hasOne(Invoice, { foreignKey: "invoice_creator", // UserId -> invoice_creator });


1 Answers

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.

like image 102
Diosney Avatar answered Sep 20 '22 00:09

Diosney