Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SergProduction/99631a6499644697e5f7a091e98bb3ec to your computer and use it in GitHub Desktop.
Save SergProduction/99631a6499644697e5f7a091e98bb3ec to your computer and use it in GitHub Desktop.
Automatically generates migration files from your sequelize models
/*
check next problenm:
Property and value:
references
defaultValue
onDelete
onUpdate
Tyoes:
Sequelize.ENAM
Sequelize.ARRAY
Sequelize.NOW
*/
const models = require("../src/models")
const Sequelize = require("sequelize")
const fs = require("fs")
const sequelize = new Sequelize(
'database',
'user',
'pass',
{
host: '127.0.0.1',
dialect: 'postgres',
}
);
const cliArgs = process.argv.slice(2)
if (cliArgs.length === 0) {
console.log(`
Missing required arguments: dirname
Before create dirname. Script won't do it for you
Example: node file.js dirname
`)
return
}
const dirname = cliArgs[0]
for (let modelName in models) {
if (modelName.toLocaleLowerCase() === 'sequelize') continue
const model = models[modelName]
let attributes = model.rawAttributes;
for (let column in attributes) {
delete attributes[column].Model;
delete attributes[column].fieldName;
delete attributes[column].field;
for (let property in attributes[column]) {
if (property.startsWith('_')) {
delete attributes[column][property];
}
}
if (typeof attributes[column]['type'] !== 'undefined') {
if (
typeof attributes[column]['type']['options'] !== 'undefined'
&& typeof attributes[column]['type']['options'].toString === 'function'
) {
attributes[column]['type']['options'] = attributes[column]['type']['options'].toString(sequelize);
}
if (
typeof attributes[column]['type'].toString === 'function'
) {
if (attributes[column]['type'].toString(sequelize).includes('TIMESTAMP')) {
attributes[column]['type'] = 'Sequelize.DATE'
}
else if (attributes[column]['type'].toString(sequelize) === 'VARCHAR(255)') {
attributes[column]['type'] = 'Sequelize.STRING'
}
else if (attributes[column]['type'].toString(sequelize).includes('VARCHAR')) {
attributes[column]['type'] = `Sequelize.STRING(${attributes[column]['type']._length})`
}
else {
attributes[column]['type'] = 'Sequelize.' + attributes[column]['type'].toString(sequelize);
}
}
}
}
let schema = JSON.stringify(attributes, null, 2);
let tableName = models[modelName].tableName;
schema = schema.split('\n').map((line) => ' '.repeat(6) + line).join('\n');
schema = schema.replace(/"/g, '', )
// console.log({ tableName, schema })
let template = `'use strict';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable('${tableName}', ${schema}
)
},
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable(${tableName});
}
};`
let d = new Date();
let filename = [d.getFullYear(), d.getMonth() + 1, d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds()]
.map((num) => num <= 60 && (num + 100).toString().substring(1) || num)
.join('') + `-${models[modelName].tableName}`;
fs.writeFileSync(`./${dirname}/${filename}.js`, template);
};
console.log('Finished!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment