Reputation: 1040
I have some fields that are very common. (CreatedBy, CreatedDate, LastUpdatedBy, LastUpdatedDate)
.
When I create a model, is there any way I can inherit these properties in my model?
I looked into the sequelize docs. But could not find anything relevant there.
Currently I am specifying these properties in each and every model I create:
const Sequelize = require('sequelize');
const conn = require('../common/mssql-connection');
const Member = conn.define('Member', {
id: {
type: Sequelize.INTEGER,
field: "Id",
autoIncrement: true,
primaryKey: true
},
name: {
type: Sequelize.STRING,
field: "Name"
},//Everything below this line is repetitive in other models. Inheritance would be useful here.
createdDate: {
type: Sequelize.DATE,
field: "CreatedDate"
},
createdBy: {
type: Sequelize.STRING,
field: "CreatedBy"
},
lastUpdatedDate: {
type: Sequelize.DATE,
field: "LastUpdatedDate"
},
lastUpdatedBy: {
type: Sequelize.STRING,
field: "LastUpdatedBy"
}
})
module.exports = Member;
Upvotes: 1
Views: 1151
Reputation: 4603
I didn't manage to find a "standard" way either, but you can intercept the original define function of the Sequelize constructor, taking care of your default fields:
const originalDefine = Sequelize.prototype.define;
Sequelize.prototype.define = function(tableName,fields){
return originalDefine.call(this,tableName, {
createdBy: { type: Sequelize.DataTypes.STRING,defaultValue:"default 'createdBy' value!!!!" },
...fields
})
}
Then create your Sequelize instance..
const sequelize = new Sequelize(...)
Upvotes: 3