Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zazapeta/58545052a0d7ff7596f7c773b9a7e65d to your computer and use it in GitHub Desktop.
Save zazapeta/58545052a0d7ff7596f7c773b9a7e65d to your computer and use it in GitHub Desktop.
How to make assiocation + migration - the programmatic way - with sequelize
const path = require('path');
const glob = require('glob');
async function associate() {
let models = {};
return Promise.all(
glob
.sync('**/*.model.js') // model pattern files
.map((modelFile) => require(path.relative(__dirname, modelFile)))
.filter((model) => {
if (model && model.modelName) {
models[model.modelName] = model;
return true;
}
return false;
})
.map((model) => model.associate(models)),
);
}
module.exports = { associate };
Simple gist on how to make assiocation and migration (with umzug) - the programmatic way - with sequelize
const { migrate } = require('../db/migrate');
const { associate } = require('../db/associate');
const { start } = require('./server');
async function main() {
await migrate();
await associate();
start();
}
main();
'use strict';
// inspired by https://github.com/sequelize/sequelize/issues/326#issuecomment-334424621
const path = require('path');
const Sequelize = require('sequelize');
const Umzug = require('umzug');
const { sequelize, openSecureSession } = require('./connect');
const umzug = new Umzug({
storage: 'sequelize',
logging: console.debug,
storageOptions: {
sequelize,
},
migrations: {
params: [sequelize.getQueryInterface(), Sequelize],
path: path.join(__dirname, './migrations'),
pattern: /^\d+[\w-]+\.migration.js$/,
},
});
async function migrate() {
let errors = false;
console.info('starting PROGRAMMATIC MIGRATION...');
console.info('directory migrations: ', path.join(__dirname, './migrations')); // migration directory
try {
await openSecureSession();
await umzug.up();
} catch (err) {
console.error('An error occur during the migration : ', err.message);
errors = true;
}
console.info(
`PROGRAMMATIC MIGRATION: terminated ${
errors ? 'with errors :(' : 'successfully'
}`,
);
}
module.exports = { migrate };
const Sequelize = require('sequelize');
const { sequelize } = require('../../../db/connect');
const Task = sequelize.define(
'task',
{
id: {
type: Sequelize.UUID,
allowNull: false,
primaryKey: true,
},
},
);
Task.modelName = 'Task';
Task.associate = function(models) {
Task.belongsTo(models.User);
};
module.exports = Task;
const Sequelize = require('sequelize');
const { sequelize } = require('../../../db/connect');
const User = sequelize.define(
'user',
{
id: {
type: Sequelize.UUID,
allowNull: false,
primaryKey: true,
},
},
);
User.modelName = 'User';
User.associate = function(models) {
User.hasMany(models.Task);
};
module.exports = User;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment