Bisexual Pride

In my last post, I mentioned that Sequelize is a popular object–relational mapping (ORM) tool in the Node.js ecosystem. In Sequelize, a model is an abstraction that represents a table in a database. One way to define a model is to extend the Model class and call the static init() method. In today’s post, I’ll show you a technique you can use to make the model definition a bit more elegant.

Defining a model

Here is an example from the Sequelize documentation. We declare a User class that extends the Model class, then we call the static init() method to define the model attributes. This is fine, but I’ve never liked having an empty class declaration and a separate call to the init() method. Wouldn’t it be nice if we could keep it all together?

// Empty class declaration
class User extends Model {}

// Separate call to init()
User.init(
{
firstName: {
type: DataTypes.STRING,
allowNull: false,
},
lastName: {
type: DataTypes.STRING,
},
},
{
sequelize,
modelName: "User",
}
);

Static initialization blocks

Using a static initialization block, we can declare arbitrary initialization logic within a class and have it executed during class evaluation. This means we can move the call to User.init() inside the class declaration. This feels more elegant to me because the model definition is contained entirely within the class declaration.

class User extends Model {
static {
User.init(
{
firstName: {
type: DataTypes.STRING,
allowNull: false,
},
lastName: {
type: DataTypes.STRING,
},
},
{
sequelize,
modelName: "User",
}
);
}
}

That’s it for today’s post—just a quick tip!