Sequelize model loader import doesn't work on top level import but only works on function import

Viewed 335

The question is little unclear as bug itself is unclear in its way. The main question would be what are the possible cases which can lead to empty sequelize model loder.

user.js

const db = require('../db/models');
async testFunc function(data){
return new Promise((resolve, reject)=>{
      try{
          let user = await db.User.findOne({where:{id:data.id}});
           resolve(user)
       }catch(error){reject(error)}
})
}
module.exports={
testFunc
}

This is snippet of module defined which works fine on its own. But let's say if its used in another module the db is not loaded so throws error db.User is undefined

user.js

async testFunc function(data){
return new Promise((resolve, reject)=>{
      const db = require('../db/models');
      try{
          let user = await db.User.findOne({where:{id:data.id}});
           resolve(user)
       }catch(error){reject(error)}
})
}
module.exports={
testFunc
}

Current workaround is require model loader inside each function(there are other similar functions too).

Just throwing the question to know possible mistakes and to find the better approach.

1 Answers

You question seems to be pointing to how can you import modules Asyncronously insode promises:

  1. CommonJS

The traditional and most common way to import modules is using the CommonJS syntax

const React = require('react');
  1. ECMA Script Modules

Second way, which is gaining popularity, especially in React and Angular ecosystem, is the EcmaScript Modules:

import { <function> } from './index.js';
  1. Dynamic Import

Third is Dynamic Import, which is what you need in your second example to dynamically load modules when do your DB related operations.

This is what you need in your second example. To dynamically load modules when do your DB related operation

async testFunc function(data){
return new Promise((resolve, reject)=>{
      const db = require('../db/models');
      import('./db/models').then(dialogBox => {
              let user = await db.User.findOne({where:{id:data.id}});
              resolve(user)
              })
              .catch(error => {
                reject(error);
              })
           })

The result of the DB Models is a Promise. Once the module is completely loaded, the Promise is fulfilled with it.

Related