1
\$\begingroup\$

I'm learning how to use SequelizeJS. What i found was that (at least for me) the definition of the DB model was too invasive in my code when creating object. I was thinking that the user of your model should not have to learn how to use sequelize (or even that i use it at all)

So I created 2 class that add a layer on top of the model, I would want to know if it is normal/OK as the abstraction is already something that Sequelize aim to provide. I would also welcome critics of my abastraction

Models classes :

import { Sequelize, Model, DataTypes } from 'sequelize';

const sequelize = new Sequelize({
    dialect: 'sqlite',
    storage: 'database.sqlite'
  });



export class User {
    public sqlObject: Promise<UserModel>;

    constructor(
        public username: string,
        public birthdate?: Date,
        public team?: Team
    ) {
        if(team) {
            this.createWithTeam(team);
        } 
    }

    private async createWithTeam(team: Team) {
        const sql = await team.sqlObject;
        console.dir(sql);
        (sql as any).createUser({
           username: this.username,
           birthdate: this.birthdate, 
        });
    }
}

export class Team {
    public sqlObject: Promise<TeamModel>;

    constructor(
        public name: string
    ) {
        this.sqlObject = TeamModel.findOrCreate({
            where: { name: this.name }
        }).then(([o]) => o);
    }
}


class UserModel extends Model {
    static TeamModel: any;
}
UserModel.init({
  username: DataTypes.STRING,
  birthday: DataTypes.DATE
}, { sequelize, modelName: 'user' });

class TeamModel extends Model {
    static UserModel: any;
};
TeamModel.init({
    name: DataTypes.STRING
}, { sequelize, modelName: 'team' });
TeamModel.UserModel = TeamModel.hasMany(User);
UserModel.TeamModel = UserModel.belongsTo(TeamModel);

Usage :

const team1 = new Team('Belgium Red Devils');
const player1 = new User('Laurent', new Date('01-01-1990'), team1);
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.