Sequelize-typescript: get Model from sequelize.models[name: string]

Created on 2 Aug 2017  路  4Comments  路  Source: RobinBuschmann/sequelize-typescript

I was wandering if there is a way to access the models from sequelize.models.

I found this project, but the function "getModel" it will just return an any type:
https://github.com/alexjoverm/unnamed-server/blob/master/src/modules/db/db.service.ts

Do you have any suggestion how to make it work?

Most helpful comment

@JustGreg Try this one:

interface ModelClass<T> {
    new(values?: any, options?: IBuildOptions): T;
}
function getModel<T>(modelName: string): ModelClass<T> & typeof Model {
    return sequelize._[modelName] as any;
}

You want typeof Model, not an instance of Model :)

All 4 comments

Hey @JustGreg, you can access models by key like this:

import {Sequelize} from 'sequelize-typescript';
const sequelize = new Sequelize(...);
sequelize._['User'].findAll(...)

or

import {Sequelize} from 'sequelize-typescript';
const sequelize = new Sequelize(...);
sequelize._.User.findAll(...)

I will add a more reasonable way in the future. I admit, sequelize._['User'] is ugly somehow.

Thank you @RobinBuschmann ,

I just tried to add this to the function getModel but I can't get the types of the selected model.

  public getModel<T>(modelName: string): Model<T> {
    return this.db._[modelName];
  }

so i can use:

  this.db.getModel<User>('User');

Typescript error: Type 'typeof Model' is not assignable to type 'Model<T>'. Property '$add' is missing in type 'typeof Model'.'

@JustGreg Try this one:

interface ModelClass<T> {
    new(values?: any, options?: IBuildOptions): T;
}
function getModel<T>(modelName: string): ModelClass<T> & typeof Model {
    return sequelize._[modelName] as any;
}

You want typeof Model, not an instance of Model :)

That works great. Thank you!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

oscarcalvo picture oscarcalvo  路  3Comments

mikew picture mikew  路  4Comments

nandox5 picture nandox5  路  3Comments

CampaUTN picture CampaUTN  路  4Comments

josecolella picture josecolella  路  4Comments