Skip to content

Instantly share code, notes, and snippets.

  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save codesword/c9b847bc3af2e871ca33be607ffdb3d8 to your computer and use it in GitHub Desktop.
const Sequelize = require('sequelize');
const models = require('./models');
const fs = require('fs');
// delete models.default;
const sequelize = new Sequelize(
'',
'',
'', {
host: '',
dialect: 'postgres',
}
);
for(let model in models) {
if (!(models[model] instanceof Sequelize.Model)) break;
let attributes = models[model].attributes;
for(let column in attributes) {
delete attributes[column].Model;
delete attributes[column].fieldName;
const field = attributes[column].field;
delete attributes[column].field;
delete attributes[column].validate;
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') {
attributes[column]['type'] = attributes[column]['type'].toString(sequelize);
}
const attribute = Object.assign({}, attributes[column]);
delete attributes[column];
attributes[field] = attribute;
}
}
// console.log(attributes)
let schema = JSON.stringify(attributes, null, 2);
let tableName = models[model].tableName;
let indexes = ['\n'];
if(models[model].options.indexes.length) {
models[model].options.indexes.forEach((obj) => {
indexes.push(' .then(() => {');
indexes.push(' return queryInterface.addIndex(');
indexes.push(` '${tableName}',`);
indexes.push(` ['${obj.fields.join("','")}']`);
let opts = {};
if(obj.name) {
opts.indexName = obj.name;
}
if(obj.unique === true) {
opts.indicesType = 'UNIQUE';
}
if(obj.method === true) {
opts.indexType = obj.method;
}
if(Object.keys(opts).length) {
indexes.push(` , ${JSON.stringify(opts)}`)
}
indexes.push(' )');
indexes.push(' })');
});
}
schema = schema.split('\n').map((line) => ' ' + line).join('\n');
let template = `
module.exports = {
up(queryInterface, Sequelize) {
return queryInterface.createTable('${tableName}',
${schema})
},
down(queryInterface, Sequelize) {
return 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[model].tableName}`;
fs.writeFileSync(`./tmp2/${filename}.js`, template);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment