Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
Create Intermediate BaseModel Class for Sequelize

I am using Sequelize as Data ORM.

I have a simple User Class.

import { Model } from "sequelize";
class User extends BaseModel {

}
export default User;

and I am able to use the User class like this User.findByPk(1) Sequelize findByPk

What I want is a BaseModel Class which will extend Sequelize Model class so that I can put some common methods in BaseClass.

For Example: Instead of using findByPk, I would want to define find method in BaseModel which will call findByPk on the Inherited class, but I am unable to find any solution to get child reference in Parent class.

something like static in PHP.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Here how you can do it:

Abstract(parent) class :

import { Model } from "sequelize";

export default abstract class BaseModel <T,U>
    extends Model<T,U>
{

    protected myMethod(){}

}

User(child) class:

import { DataTypes, Model, Optional } from 'sequelize'
import { sequelizeConnection } from "../helpers/databaseHelper"
import BaseModel from "../models/BaseModel";

interface UserAttributes {
    id: number;
    createdAt?: Date;
    updatedAt?: Date;
    deletedAt?: Date;
}
export interface UserInput extends Optional<UserAttributes, "id"> {}

export default 
class User<T=UserAttributes,U=UserInput> // <-- Pass the same generic construction as AbstractModel
extends BaseModel <T,U>  // <-- Here the trick
implements UserAttributes{

    public id!: number; 
    public name!: string;

    // timestamps!
    public readonly createdAt!: Date;
    public readonly updatedAt!: Date;
    public readonly deletedAt!: Date;

}
User.init({
    id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
    },
// Your attributes
},
 {
    timestamps: true,
    sequelize: sequelizeConnection,
    paranoid: true
})
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!