Skip to content

Instantly share code, notes, and snippets.

@matsuaki-jp

matsuaki-jp/doMigration.ts

Last active Aug 30, 2020
Embed
What would you like to do?
sequelize do migration
import { Writable } from 'stream';
import { Socket } from 'net';
import { connectionConfig } from './settings'
import { Client } from 'ssh2';
import { Sequelize } from 'sequelize';
import { Umzug } from 'umzug';
const net = require('net');
/**
* 処理成功時
* @returns void
*/
const succcessRes = () => {
console.log('finished')
process.exit();
}
/**
* 処理失敗時
* @param {} err
*/
const failsRes = (err) => {
console.log(err)
process.exit(1);
}
/**
* migration時の処理を生やす
* @param {string} methodName
* @param {Umzug} instance
*/
const updateMethod = (methodName:string, instance:Umzug) =>{
if(methodName === 'up'){
(async () => {
// Checks migrations and run them if they are not already applied. To keep
// track of the executed migrations, a table (and sequelize model) called SequelizeMeta
// will be automatically created (if it doesn't exist already) and parsed.
await instance.up();
})();
}
if(methodName === 'down'){
(async () => {
await instance.down();
})();
}
}
/**
* 主処理
* @param {NodeJS.Process} process
* @returns void
*/
const main = (process:NodeJS.Process):void => {
const methodName = process.argv[2]
// sequelize setting
const sequelizeSetting = new Sequelize(
connectionConfig.dbname,
connectionConfig.dbUsername,
connectionConfig.dbPassword,
{
host: connectionConfig.localhost,
dialect: connectionConfig.dbDialect,
port:connectionConfig.localPort,
schema:connectionConfig.dbSchema,
pool: {
max: 5,
min: 0,
idle: 10000
}
});
const UmzugSetting = new Umzug({
migrations: {
path: connectionConfig.migrationsPath,
params: [
sequelizeSetting.getQueryInterface()
]
}
});
// // port forwardstart
console.log('server create')
const conn:Client = new Client();
console.log('cliant create')
conn.on('ready', function() {
console.log('connected')
console.log('port foward')
console.log('command:' + methodName)
updateMethod(methodName, UmzugSetting)
}).connect({
host: connectionConfig.sshHost,
port: connectionConfig.sshPort,
username: connectionConfig.bastionUserName,
privateKey: require('fs').readFileSync(connectionConfig.batsionKeyPath),
passphrase : connectionConfig.keyPassphrase
});
net.createServer(
(sock:Socket) => {
conn.forwardOut(
connectionConfig.localhost,
sock.remotePort,
connectionConfig.dbHost,
connectionConfig.dbPort,
(err:Error, stream:Writable) => {
if (err) return sock.end();
stream.pipe(sock).pipe(stream);
});
}).listen(connectionConfig.localPort);
}
main(process);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment