sequelize / express-example

A proposal for the usage of Sequelize within an Express.JS application.
MIT License
2.5k stars 770 forks source link

dynamic imports do not work for defining models #116

Closed kjoedion closed 1 year ago

kjoedion commented 1 year ago

Using dynamic imports in order to define models does not work. It works fine when manually declaring the imports, but I'd prefer just being able to create model files in a directory and my app knowing they exist dynamically.

db.js:

import { Sequelize } from 'sequelize'
import env from './env.js'

const db = new Sequelize(
    env.DB_NAME,
    env.DB_USERNAME,
    env.DB_PASSWORD,
    {
        host: env.DB_HOST,
        port: env.DB_PORT,
        dialect: env.DB_DIALECT,
        logging: false,
    },
)

export default db

server.js:

import fg from 'fast-glob'
import path from 'path'
import app from '../providers/app.js'
import db from '../providers/db.js'
import env from '../providers/env.js'

fg.sync([
    './app/models/**/*.js',
    './app/routes/**/*.js',
]).forEach(async (file) => {
    await import(path.resolve(file))
})

await db.sync({ alter: true })

app.listen(env.APP_PORT, () => {
    console.log(`App listening on ${env.APP_HOST}:${env.APP_PORT}`)
})

The models do not get defined this way. Whats funny is my routes for express are done in the same way, and they work fine.

If I change it to non-dynamic imports, the sequelize definitions work fine:

import '../models/user.js'
import '../routes/index.js'

Why doesn't sequelize pick up the definitions when done via dynamic imports as opposed to manual imports?

ephys commented 1 year ago

forEach is sync and cannot return a promise, so you're not awaiting the async callback passed to it. Use array.map and Promise.all

kjoedion commented 1 year ago

forEach is sync and cannot return a promise, so you're not awaiting the async callback passed to it. Use array.map and Promise.all

Thank you, I didn't even think of that. My bad for blaming sequelize.

I changed my code to a for instead and it works:

const files = await globby([
    '../models/**/*.js',
    '../routes/**/*.js',
], {
    cwd: './app/entries',
})

for (const file of files) {
    await import(file)
}

await db.sync({ alter: true })