sequelize icon indicating copy to clipboard operation
sequelize copied to clipboard

[Typescript] Many weird behaviors happens with Sequelize included type definitions

Open TitaneBoy opened this issue 7 years ago • 9 comments

What are you doing?

Since I've updated Sequelize to v5 and using native provided type definition, I can't use models properly to do some request.

For example

import debug = require('debug');
import { join } from 'path';
import { modelInstance, SequelizeSingleton } from './core/singletons/sequelizeSingleton';

const mySequelize = SequelizeSingleton.getInstance().sequelizer;
const debugConsole = debug('Ruby');

const session = mySequelize.import(join(process.cwd(), 'build/models/Sessions.js'));

/**
 * Asynchronously verify if a user is authenticated by verifying if a session ID exists in the Sessions database table.
 * If it is, the Promise will return the row associated with the session ID in the Session database table.
 *
 * @export
 * @param {(string | number)} sid The session ID to check in the Sessions database table
 * @returns {void}
 */
export function verifyAuthentication(sid: string | number) {
  return new Promise<modelInstance>((resolve, reject) => {
    mySequelize.authenticate().then(() => {
      return mySequelize.sync().then(() => {
        return session.findByPk(sid, {attributes: [ 'data' ]}).then((sessionData) => {
          if (!sessionData) {
            resolve();
          } else {
            resolve(sessionData);
          }
        }).catch((error) => {
          reject(error);
        });
      });
    }).catch((err) => {
      debugConsole('Unable to authenticate to the database:', err);
      reject(err);
    });
  });
}

This should not, normally, report any errors but I got this in my IDE:

image

image

image

image

As you can see, i'm trying to import my "Sessions" model and to make a "findByPk" request, but Typescript is saying the error you can see in my previous screenshots. And when I mouse hover on the "then" word, it shows me an "any" return type, instead of a Promise type.

Also, When trying to see the findByPk with my cursor, I can see this:

image

But When clicking on the function to get the definition, It take me to this: image

As you can see, it shoud returns a Promise but when I mouse hover the function, it says that it return an "any" type

Here is my "Session" model definition:

import * as sequelize from 'sequelize';

module.exports = (sequelizeInstance: sequelize.Sequelize) => {
  return sequelizeInstance.define('Sessions', {
    data: {
      allowNull: true,
      type: sequelize.TEXT,
    },
    expires: {
      allowNull: true,
      type: sequelize.DATE,
    },
    sid: {
      allowNull: false,
      primaryKey: true,
      type: sequelize.STRING,
    },
  }, {
    freezeTableName: true,
    tableName: 'Sessions',
    underscored: true,
  });
};

Here is my dependencies:

"dependencies": {
    "@types/debug": "^4.1.2",
    "bcryptjs": "2.4.3",
    "body-parser": "1.18.3",
    "commander": "2.19.0",
    "connect-session-sequelize": "6.0.0",
    "cookie": "0.3.1",
    "cookie-parser": "1.4.4",
    "cors": "2.8.5",
    "debug": "^4.1.1",
    "express": "4.16.4",
    "express-jwt": "5.3.1",
    "express-session": "1.15.6",
    "express-unless": "0.5.0",
    "formidable": "1.2.1",
    "helmet": "3.16.0",
    "hpp": "0.2.2",
    "jsonwebtoken": "8.5.0",
    "morgan": "1.9.1",
    "nodemailer": "5.1.1",
    "passport": "0.4.0",
    "passport-http": "0.3.0",
    "passport-local": "1.0.0",
    "pdfkit": "0.9.0",
    "pg": "7.8.2",
    "pg-hstore": "2.3.2",
    "rxjs": "6.4.0",
    "sequelize": "5.1.0",
    "serve-favicon": "2.5.0",
    "serve-static": "1.13.2",
    "winston": "3.2.1",
    "ws": "6.2.0"
  },
  "devDependencies": {
    "@openapitools/openapi-generator-cli": "0.0.8-4.0.0-beta2",
    "@types/bcryptjs": "2.4.2",
    "@types/body-parser": "1.17.0",
    "@types/chai": "4.1.7",
    "@types/chai-as-promised": "7.1.0",
    "@types/cookie": "0.3.2",
    "@types/cookie-parser": "1.4.1",
    "@types/cors": "2.8.4",
    "@types/express": "4.16.1",
    "@types/express-jwt": "0.0.41",
    "@types/express-session": "1.15.12",
    "@types/express-unless": "0.5.1",
    "@types/formidable": "1.0.31",
    "@types/helmet": "0.0.43",
    "@types/hpp": "0.2.1",
    "@types/jsonwebtoken": "8.3.2",
    "@types/mocha": "5.2.6",
    "@types/morgan": "1.7.35",
    "@types/node": "11.11.3",
    "@types/nodemailer": "4.6.6",
    "@types/passport": "1.0.0",
    "@types/passport-http": "0.3.7",
    "@types/passport-local": "1.0.33",
    "@types/pdfkit": "0.7.36",
    "@types/ws": "6.0.1",
    "apidoc": "0.17.7",
    "chai": "4.2.0",
    "chai-as-promised": "7.1.1",
    "mocha": "6.0.2",
    "mocha-jenkins-reporter": "0.4.1",
    "nodemon": "1.18.10",
    "nyc": "13.3.0",
    "ts-node": "8.0.3",
    "tslint": "5.14.0",
    "tslint-eslint-rules": "5.4.0",
    "typedoc": "0.14.2",
    "typescript": "3.3.3333",
    "vrsource-tslint-rules": "6.0.0"
  }

What do you expect to happen?

After importing models in Sequelize, using the import returned value (stored in variable) to make normal requests like findByPk, findAll, etc...

What is actually happening?

Getting Typescript error with type definition

Dialect: postgres Sequelize version: 5.1.0

Thank you in advance for your help

TitaneBoy avatar Mar 19 '19 16:03 TitaneBoy

Another Question: If in some file, we are importing models inside a sequelize variable like this:

image

And if in another file, we are using this sequelize variable to get an imported model, is it correct to do this ?

const measurementModel = this._sequelizer.model('measurementV2');
          measurementModel.find({where: {id}})

image

Because when I'm doing this, I'm getting an typescript error on the "find" function

image

TitaneBoy avatar Mar 19 '19 16:03 TitaneBoy

  1. The sequelize typings as found on DT aren't really representative of v5 (they were also incorrect for v4) as there's no real separation between a model class and a model instance anymore (they used to be distinct classes in v3).

  2. define and import return typeof Model which is an abstract class, this error is somewhat expected as you're not suppose to instantiate the Model class, you must cast the returned class to whatever you need. 2.1) We could remove the abstract keyword to make this semi-functional, I don't think this is a good idea tho as it hides underlying problem.

  3. Functions that return anonymous classes are impossible to model correctly in TS, this affects both import and define calls in sequelize.

  4. I strongly suggest that you migrate your models to use extend from the sequelize model and use the static init method to initialize them in a central file/location.

@sushantdhiman We should look into deprecating import and define for this reason, they are entirely opaque to any static analysis and updating the docs to discourage .define with TS.

SimonSchick avatar Mar 19 '19 22:03 SimonSchick

@SimonSchick . Thank you for your detailed answer... But is there any Typescript examples we can base on to code with Sequelize ? Because Since i'm taking example in the official Sequelize documentation, our last suggestion (No. 4) doesn't seem to be in the last version of Sequelize documentation...

If there is no example, can you please provides some examples based on the model I provided in this issue ? Because I'm not sure to understand some of your points (2 and 4) or how it must be translated in Typescript language.

Thank you in advance again for your help and asnwer

TitaneBoy avatar Mar 20 '19 14:03 TitaneBoy

@SimonSchick If I understand well your last point (correct me please if I'm wrong), you suggest that instead of doing this:

import * as sequelize from 'sequelize';

module.exports = (sequelizeInstance: sequelize.Sequelize) => {
  return sequelizeInstance.define('Sessions', {
    data: {
      allowNull: true,
      type: sequelize.TEXT,
    },
    expires: {
      allowNull: true,
      type: sequelize.DATE,
    },
    sid: {
      allowNull: false,
      primaryKey: true,
      type: sequelize.STRING,
    },
  }, {
    freezeTableName: true,
    tableName: 'Sessions',
    underscored: true,
  });
};

we must create...classes that extends sequelize.Model ? and then instanciate this class with ...static init ? It looks so much different from the official documentation that still continues to use sequelize.define('tableName', options)

TitaneBoy avatar Mar 20 '19 15:03 TitaneBoy

See http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-init

Maybe the actual (new) definition of the define method gives you a good idea what is going on as well:

https://github.com/sequelize/sequelize/blob/0b868c837bb2d2a4ea1f9eeb6367f86aa7ef1f47/lib/sequelize.js#L350-L359

SimonSchick avatar Mar 20 '19 15:03 SimonSchick

@SimonSchick ..Thank you for your answer...It looks to be more clear now...I'm working on it to see if I understood well. But If I can bring a point here, I think there is an error on the type definition OR the Sequelize documentation.

On the static init function documentation , we can see 'options.modelName' as a string:

image

But when exploring the type definition of static init function, we can see this:

image

image

ModelOptions: image

ModelNameOptions: image

There is no modelName string attribute for init's options and it seems there is, instead, an "name" object attribute

I think the doc of this function is not up to date according to the type definition.

TitaneBoy avatar Mar 20 '19 16:03 TitaneBoy

@SimonSchick Hello Simon.. I've refactored my code to incorporate your suggestion you gave me previously (the point 4) but something is still not working and I don't understand what exactly...

Here are what I have in my files:

model\Session.ts

import { Model } from 'sequelize';
export class SequelizeModel extends Model {}

export default function session(sequelizeInstance: sequelize.Sequelize) {
  const options: sequelize.InitOptions = {
    freezeTableName: true,
    name: {singular: 'Session', plural: 'Sessions'},
    sequelize: sequelizeInstance,
    tableName: 'Sessions',
    underscored: true,
  };

  const attributes = {
    data: {
      allowNull: true,
      type: sequelize.TEXT,
    },
    expires: {
      allowNull: true,
      type: sequelize.DATE,
    },
    sid: {
      allowNull: false,
      primaryKey: true,
      type: sequelize.STRING,
    },
  };

  const sessionModel = SequelizeModel;
  sessionModel.init(attributes, options);
  return sessionModel;
}

SequelizeSingleton.ts

import session from '../../../models/sessions';

export class SequelizeSingleton {
  private static sequelizerSingleton: SequelizeSingleton;
  private _sequelizer: Sequelize;
  private _models: Map<string, typeof SequelizeModel>;
...

  public model(name: string) {
    if (this._models.has(name)) {
      return this._models.get(name);
    }

    throw new Error(`No model with name ${name} exists`);
  }

  protected importDatabaseModels() {
    this._models.set('Sessions', session(this._sequelizer));  // Here, we are initialiazing "session" model and we store it in a map
  }

  get sequelizer() {
    return this._sequelizer;
  }

  private constructor(database: string, options ?: Options) {
    if (typeof database === 'string') {
      this._sequelizer = new Sequelize(database,
        {define: {timestamps: false}, logging: false, operatorsAliases: false});
    }

    if (options !== undefined) {
      options.define = (options.define) ? (options.define) : {timestamps: false};
      options.logging = (options.logging) ? (options.logging) : (false);
      options.operatorsAliases = (options.operatorsAliases) ? (options.operatorsAliases) : (false);
      this._sequelizer = new Sequelize(database, options);
    }
    this.importDatabaseModels();
  }
}

scripts/session.ts

import debug = require('debug');
import { modelInstance, SequelizeSingleton } from './core/singletons/sequelizeSingleton';

const session = SequelizeSingleton.getInstance().model('Sessions');

const mySequelize = SequelizeSingleton.getInstance().sequelizer;
const debugConsole = debug('Ruby');

/**
 * Asynchronously verify if a user is authenticated by verifying if a session ID exists in the Sessions database table.
 * If it is, the Promise will return the row associated with the session ID in the Session database table.
 *
 * @export
 * @param {(string | number)} sid The session ID to check in the Sessions database table
 * @returns {void}
 */
export function verifyAuthentication(sid: string | number) {
  return new Promise<modelInstance>((resolve, reject) => {
    mySequelize.authenticate().then(() => {
      return mySequelize.sync().then(() => {
        return session.findByPk(sid, {attributes: [ 'data' ]}).then((sessionData) => {
          if (!sessionData) {
            resolve();
          } else {
            resolve(sessionData);
          }
        }).catch((error) => {
          reject(error);
        });
      });
    }).catch((err) => {
      debugConsole('Unable to authenticate to the database:', err);
      reject(err);
    });
  });
}

The only problem is when I'm trying to see the return type of model functions or the return type of Sequelize functions, I always have an "any" type..

Here are some examples:

image

image

As you can see, the return type of the model.findByPK function is "any", instead of a "Promise" type. Also, when I mouse hover on the "then" function of "mySequelize.authenticate()" function, it says it is an "any" type, which should not be this type.

I don't know what exactly I'm missing here or what I'm doing wrong. As I said, I've tried to follow your previous advice (point 4 about extending a class with the "Model" abstract class) but I still can't have the proper returned type of Model functions or event Sequelize function.

Can you help me please to figure out what is wrong with my approach ?

TitaneBoy avatar Mar 21 '19 16:03 TitaneBoy

This is what I see in my file: image

In my file, the "authenticate" function returns an "any" type

In type definition file: image

In the type definition file, the authenticate function returns a "Promise" type

TitaneBoy avatar Mar 21 '19 17:03 TitaneBoy

There's a few issues here that, I now realise, are badly explained or not explained at all, I am adding a new section to the documentation.

SimonSchick avatar Mar 21 '19 18:03 SimonSchick