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.
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
})