Last active
March 15, 2024 14:36
-
-
Save ngustavo/5468f4c795d99a64864ab118352c63fc to your computer and use it in GitHub Desktop.
Sequelize ES6 model loader for sqlite
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs from 'fs'; | |
import path from 'path'; | |
import { fileURLToPath } from 'url'; | |
import Sequelize from 'sequelize'; | |
const models = {}; | |
const filename = fileURLToPath(import.meta.url); | |
const dirname = path.dirname(filename); | |
const basename = path.basename(filename); | |
const sequelize = new Sequelize({ | |
dialect: 'sqlite', | |
storage: path.resolve(dirname, './tmp.db'), | |
}); | |
(async () => { | |
const files = fs | |
.readdirSync(dirname) | |
.filter((file) => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')); | |
await Promise.all(files.map(async (file) => { | |
const module = await import(path.join(dirname, file)); | |
const model = module.default(sequelize, Sequelize); | |
models[model.name] = model; | |
})); | |
Object.keys(models).forEach((modelName) => { | |
if (models[modelName].associate) { | |
models[modelName].associate(models); | |
} | |
}); | |
})(); | |
export default { models, sequelize, Sequelize }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment