Created
March 20, 2019 08:59
-
-
Save AlekseyA/59d874190d15e5fe56f0977d8e070c10 to your computer and use it in GitHub Desktop.
Creating sequelize migrations from existing models
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
| const fs = require('fs'); | |
| const db = require('../models'); | |
| console.log('Start creating migration files...'); | |
| /* eslint-disable guard-for-in,no-restricted-syntax */ | |
| for (const model in db) { | |
| const { attributes } = db[model]; | |
| for (const column in attributes) { | |
| delete attributes[column].Model; | |
| delete attributes[column].fieldName; | |
| delete attributes[column].field; | |
| for (const property in attributes[column]) { | |
| if (property.startsWith('_')) { | |
| delete attributes[column][property]; | |
| } | |
| if (property === 'type') { | |
| const type = attributes[column].type.constructor.name; | |
| let sequelizeTypeString = `${type}`; | |
| if (type === 'ARRAY') { | |
| const arrayType = attributes[column].type.type.constructor.name; | |
| sequelizeTypeString = `${sequelizeTypeString}(Sequelize.${arrayType})`; | |
| } | |
| attributes[column].type = `\`Sequelize.${sequelizeTypeString}\``; | |
| } | |
| } | |
| } | |
| let schema = JSON.stringify(attributes, null, 2); | |
| const { tableName } = db[model]; | |
| if (schema) { | |
| schema = schema.replace(new RegExp('"`|`"', 'ig'), ''); | |
| } | |
| const template = `'use strict'; | |
| module.exports = { | |
| up: (queryInterface, Sequelize) => { | |
| return queryInterface.createTable('${tableName}', ${schema}); | |
| }, | |
| down: (queryInterface, Sequelize) => { | |
| return queryInterface.dropTable(${tableName}); | |
| } | |
| };`; | |
| if (db[model].tableName !== undefined) { | |
| fs.writeFileSync(`./src/migrations/initial_${db[model].tableName}.js`, template); | |
| } | |
| } | |
| console.log('Finished'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment