0

I am refactoring my index file that creates all my models in Sequelize to use imports instead of require with the switch to Node v14 and Sequelize v6 and modules. But I am stuck on this weird error:

TypeError: (intermediate value) is not a function at file:///C:/.../models/index.js:41:6 at async Promise.all (index 0)

Here is the code block where it is happening:

fs.readdir(__dirname, (err, files) => {
    console.log('in the readdir!!');
    if (err) {
        console.log({ err });
    } else {
        console.log('the else!');
        console.log({ files });
        const promise_arr = files
            .filter((file) => {
                return (
                    file.indexOf('.') !== 0 &&
                    file !== basename &&
                    file.slice(-3) === '.js'
                );
            })
            .map(async (file) => {
                // const model = sequelize['import'](path.join(__dirname, file));
                console.log({ file });
                console.log({ __dirname });
                return (
                    await import('file:///' + path.join(__dirname, file))
                )(sequelize, Sequelize.DataTypes);
            });
        console.log({ promise_arr });
        Promise.all(promise_arr)
            .then((models) => {
                models.forEach((model) => (db[model.name] = model));
                associateCB();
            })
            .catch((e) => console.log({ e }));
    }
});

function associateCB() {
    console.log('associateCB with: ', db);
    Object.keys(db).forEach((modelName) => {
        if (db[modelName].associate) {
            db[modelName].associate(db);
        }
    });
    console.log(1, { db });
}

And the error says it is happening on this line: )(sequelize, Sequelize.DataTypes);

dmikester1
  • 1,374
  • 11
  • 55
  • 113
  • The line you indicate is a function invocation. The error message says something is not a function. It seems clear to me that the value produced by `await import('file:///' + path.join(__dirname, file))` is not a function; find out what it is. – apsillers Jul 07 '21 at 15:24
  • OK, so I did this: `const fileImport = await import('file:///' + path.join(__dirname, file)); console.log(typeof fileImport);`. And I got a type of object. – dmikester1 Jul 07 '21 at 15:28
  • 1
    That's it then! You can't perform the function call `fileImport(sequelize, Sequelize.DataTypes)` if `fileImport` is not a function. – apsillers Jul 07 '21 at 15:30

1 Answers1

0

Looks like it might be a semicolon issue? See: Uncaught TypeError: (intermediate value)(...) is not a function

return (
    await import('file:///' + path.join(__dirname, file)); // <--- Add this semicolon
)(sequelize, Sequelize.DataTypes);