Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize extend Model Class in Typescript

I am working on a legacy project that we would like to migrate to Typescript. It has models defined in the following format:

import Sequelize from "sequelize";

class MyModel extends Sequelize.Model {
  public static init(sequelize) {
    const attributes = {
      userId: {
        type: Sequelize.INTEGER,
        allowNull: false,
        field: "user_id"
      },
      createdAt: {
        type: Sequelize.DATE,
        field: "created_at"
      }
    };

    super.init(attributes, {
      sequelize
    });
  }
}

export default MyModel;

I would like to convert them to typescript without having to change the interface for consumers. By that I mean I want to extend Sequelize.Model and I want to define a public static init method.

I am getting the following error from Typescript on Sequelize.Model

Type 'Model<any, any>' is not a constructor function type.

And all of the research I've done points to using Sequelize.define to define models.

This being a legacy project I don't want to re-write all of my models just to conform to the types so I'm wondering how I can properly extend Sequelize.Model?

Thanks

like image 605
adampetrie Avatar asked Dec 23 '18 12:12

adampetrie


People also ask

Can you use Sequelize with TypeScript?

You can also connect different types of databases to your project while using the same code to access them. In this article, you'll learn how to use the Sequelize ORM with TypeScript. So grab your laptops, open your IDE, and let's get started!

How do I update models in Sequelize?

The Model.update() method will update your table rows with the values you passed as its first argument. The syntax of the method is as shown below: Model. update( { // values }, { // options } );

How do I sync models in Sequelize?

A model can be synchronized with the database by calling model.sync(options) , an asynchronous function (that returns a Promise). With this call, Sequelize will automatically perform an SQL query to the database. Note that this changes only the table in the database, not the model in the JavaScript side.

How do you prevent createdAt and updatedAt in Sequelize?

With timestamps: false , the generated model will omit the createdAt and updatedAt attributes. You can also opt to include only the timestamp attribute you need as shown below: const User = sequelize. define( "User", { firstName: Sequelize.


1 Answers

Try This

public static init(sequelize) {
    super.init.call(this,{ 
        id: {
        type: DataTypes.INTEGER.UNSIGNED,
        autoIncrement: true,
        primaryKey: true,
        },  
        text: {
        type: DataTypes.STRING(5000) // extra long length
        }  
    }, {
        sequelize: sequelize
    });
}
like image 186
Satya Avatar answered Nov 15 '22 08:11

Satya