Skip to content

Instantly share code, notes, and snippets.

@ngustavo
Last active March 15, 2024 14:36
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ngustavo/5468f4c795d99a64864ab118352c63fc to your computer and use it in GitHub Desktop.
Save ngustavo/5468f4c795d99a64864ab118352c63fc to your computer and use it in GitHub Desktop.
Sequelize ES6 model loader for sqlite
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