Skip to content

Commit

Permalink
refactor: use single log/warn/error methods, make output pretty (#552)
Browse files Browse the repository at this point in the history
  • Loading branch information
sushantdhiman committed Sep 23, 2017
1 parent e5a9b15 commit 5633648
Show file tree
Hide file tree
Showing 14 changed files with 89 additions and 119 deletions.
21 changes: 6 additions & 15 deletions src/commands/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,9 @@ exports.handler = async function (args) {

switch (command) {
case 'db:create':
await sequelize.query(`CREATE DATABASE ${sequelize.queryInterface.quoteIdentifier(config.database)}`, {
await sequelize.query(`CREATE DATABASE ${sequelize.getQueryInterface().quoteIdentifier(config.database)}`, {
type: sequelize.QueryTypes.RAW
}).catch(e => {
helpers.view.error(`Error: ${e.message}`);
process.exit(1);
});
}).catch(e => helpers.view.error(e));

helpers.view.log(
'Database',
Expand All @@ -34,12 +31,9 @@ exports.handler = async function (args) {

break;
case 'db:drop':
await sequelize.query(`DROP DATABASE ${sequelize.queryInterface.quoteIdentifier(config.database)}`, {
await sequelize.query(`DROP DATABASE ${sequelize.getQueryInterface().quoteIdentifier(config.database)}`, {
type: sequelize.QueryTypes.RAW
}).catch(e => {
helpers.view.error(`Error: ${e.message}`);
process.exit(1);
});
}).catch(e => helpers.view.error(e));

helpers.view.log(
'Database',
Expand All @@ -59,8 +53,7 @@ function getDatabaseLessSequelize () {
try {
config = helpers.config.readConfig();
} catch (e) {
helpers.view.error(`Error: ${e.message}`);
process.exit(1);
helpers.view.error(e);
}

config = cloneDeep(config);
Expand All @@ -82,13 +75,11 @@ function getDatabaseLessSequelize () {

default:
helpers.view.error(`Dialect ${config.dialect} does not support db:create / db:drop commands`);
process.exit(1);
}

try {
return new Sequelize(config);
} catch (e) {
helpers.view.error(`Error: ${e.message}`);
process.exit(1);
helpers.view.error(e);
}
}
4 changes: 2 additions & 2 deletions src/commands/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ exports.handler = async function (argv) {
function initConfig (args) {
if (!helpers.config.configFileExists() || !!args.force) {
helpers.config.writeDefaultConfig();
console.log('Created "' + helpers.config.relativeConfigFile() + '"');
helpers.view.log('Created "' + helpers.config.relativeConfigFile() + '"');
} else {
helpers.init.notifyAboutExistingFile(helpers.config.relativeConfigFile());
helpers.view.notifyAboutExistingFile(helpers.config.relativeConfigFile());
process.exit(1);
}
}
Expand Down
29 changes: 9 additions & 20 deletions src/commands/migrate.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,12 @@ function migrate(args) {
.then(() => migrator.pending())
.then(migrations => {
if (migrations.length === 0) {
console.log('No migrations were executed, database schema was already up to date.');
helpers.view.log('No migrations were executed, database schema was already up to date.');
process.exit(0);
}
})
.then(() => migrator.up())
.catch(err => {
console.error(err);
process.exit(1);
});
});
.then(() => migrator.up());
}).catch(e => helpers.view.error(e));
}

function migrationStatus(args) {
Expand All @@ -50,33 +46,26 @@ function migrationStatus(args) {
.then(() => migrator.executed())
.then(migrations => {
_.forEach(migrations, migration => {
console.log('up', migration.file);
helpers.view.log('up', migration.file);
});
}).then(() => migrator.pending())
.then(migrations => {
_.forEach(migrations, migration => {
console.log('down', migration.file);
helpers.view.log('down', migration.file);
});
}).catch(err => {
console.error(err);
process.exit(1);
});
});
}).catch(e => helpers.view.error(e));
}

function migrateSchemaTimestampAdd(args) {
return getMigrator('migration', args).then(migrator => {
return addTimestampsToSchema(migrator)
.then(items => {
if (items) {
console.log('Successfully added timestamps to MetaTable.');
helpers.view.log('Successfully added timestamps to MetaTable.');
} else {
console.log('MetaTable already has timestamps.');
helpers.view.log('MetaTable already has timestamps.');
}
})
.catch(err => {
console.error(err);
process.exit(1);
});
});
}).catch(e => helpers.view.error(e));
}
8 changes: 2 additions & 6 deletions src/commands/migrate_undo.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ function migrateUndo (args) {
return ensureCurrentMetaSchema(migrator).then(() => migrator.executed())
.then(migrations => {
if (migrations.length === 0) {
console.log('No executed migrations found.');
helpers.view.log('No executed migrations found.');
process.exit(0);
}
})
Expand All @@ -37,10 +37,6 @@ function migrateUndo (args) {
} else {
return migrator.down();
}
})
.catch(err => {
console.error(err);
process.exit(1);
});
});
}).catch(e => helpers.view.error(e));
}
10 changes: 3 additions & 7 deletions src/commands/migrate_undo_all.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,10 @@ function migrationUndoAll (args) {
return ensureCurrentMetaSchema(migrator).then(() => migrator.executed())
.then(migrations => {
if (migrations.length === 0) {
console.log('No executed migrations found.');
helpers.view.log('No executed migrations found.');
process.exit(0);
}
})
.then(() => migrator.down({ to: args.to || 0 }))
.catch(err => {
console.error(err);
process.exit(1);
});
});
.then(() => migrator.down({ to: args.to || 0 }));
}).catch(e => helpers.view.error(e));
}
4 changes: 1 addition & 3 deletions src/commands/model_generate.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ function ensureModelsFolder () {
helpers.path.getModelsPath() +
'). Did you run ' + clc.blueBright('sequelize init') + '?'
);
process.exit(1);
}
}

Expand All @@ -60,15 +59,14 @@ function ensureMigrationsFolder () {
helpers.path.getPath('migration') +
'). Did you run ' + clc.blueBright('sequelize init') + '?'
);
process.exit(1);
}
}

function checkModelFileExistence (args) {
const modelPath = helpers.path.getModelPath(args.name);

if (!args.force && helpers.model.modelFileExists(modelPath)) {
helpers.model.notifyAboutExistingFile(modelPath);
helpers.view.notifyAboutExistingFile(modelPath);
process.exit(1);
}
}
16 changes: 4 additions & 12 deletions src/commands/seed.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,13 @@ function seedAll (args) {
return migrator.pending()
.then(seeders => {
if (seeders.length === 0) {
console.log('No seeders found.');
helpers.view.log('No seeders found.');
return;
}

return migrator.up({ migrations: _.chain(seeders).map('file').value() });
})
.catch(err => {
console.error('Seed file failed with error:', err.message, err.stack);
process.exit(1);
});
});
}).catch(e => helpers.view.error(e));
}

function seedUndoAll (args) {
Expand All @@ -49,15 +45,11 @@ function seedUndoAll (args) {
)
.then(seeders => {
if (seeders.length === 0) {
console.log('No seeders found.');
helpers.view.log('No seeders found.');
return;
}

return migrator.down({ migrations: _.chain(seeders).map('file').reverse().value() });
})
.catch(err => {
console.error('Seed file failed with error:', err.message, err.stack);
process.exit(1);
});
});
}).catch(e => helpers.view.error(e));
}
16 changes: 4 additions & 12 deletions src/commands/seed_one.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,22 +30,14 @@ exports.handler = async function (args) {
switch (command) {
case 'db:seed':
await getMigrator('seeder', args).then(migrator => {
return migrator.up(seeds)
.catch(err => {
console.error('Seed file failed with error:', err.message, err.stack);
process.exit(1);
});
});
return migrator.up(seeds);
}).catch(e => helpers.view.error(e));
break;

case 'db:seed:undo':
await getMigrator('seeder', args).then(migrator => {
return migrator.down({ migrations: seeds })
.catch(err => {
console.error('Seed file failed with error:', err.message, err.stack);
process.exit(1);
});
});
return migrator.down({ migrations: seeds });
}).catch(e => helpers.view.error(e));
break;
}

Expand Down
18 changes: 7 additions & 11 deletions src/core/migrator.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import helpers from '../helpers/index';
import Umzug from 'umzug';
import Bluebird from 'bluebird';
import _ from 'lodash';

import helpers from '../helpers/index';

const Sequelize = helpers.generic.getSequelize();

export function logMigrator (s) {
Expand All @@ -17,24 +18,22 @@ function getSequelizeInstance () {
try {
config = helpers.config.readConfig();
} catch (e) {
console.log(e.message);
process.exit(1);
helpers.view.error(e);
}

config = _.defaults(config, { logging: logMigrator });

try {
return new Sequelize(config);
} catch (e) {
console.warn(e);
throw e;
helpers.view.error(e);
}
}

export function getMigrator (type, args) {
return Bluebird.try(() => {
if (!(helpers.config.configFileExists() || args.url)) {
console.log(
helpers.view.error(
'Cannot find "' + helpers.config.getConfigFile() +
'". Have you run "sequelize init"?'
);
Expand All @@ -45,7 +44,7 @@ export function getMigrator (type, args) {
const migrator = new Umzug({
storage: helpers.umzug.getStorage(type),
storageOptions: helpers.umzug.getStorageOptions(type, { sequelize }),
logging: console.log,
logging: helpers.view.log,
migrations: {
params: [sequelize.getQueryInterface(), Sequelize],
path: helpers.path.getPath(type),
Expand All @@ -63,10 +62,7 @@ export function getMigrator (type, args) {
return sequelize
.authenticate()
.then(() => migrator)
.catch(err => {
console.error('Unable to connect to database: ' + err);
process.exit(1);
});
.catch(e => helpers.view.error(e));
});
}

Expand Down
5 changes: 5 additions & 0 deletions src/core/yargs.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ export function _baseOptions (yargs) {
.option('url', {
describe: 'The database connection string to use. Alternative to using --config files',
type: 'string'
})
.option('debug', {
describe: 'When available show various debug information',
default: false,
type: 'boolean'
});
}

Expand Down
6 changes: 3 additions & 3 deletions src/helpers/config-helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,13 +120,13 @@ const api = {
}

if (args.url) {
console.log('Parsed url ' + api.filteredUrl(args.url, api.rawConfig));
helpers.view.log('Parsed url ' + api.filteredUrl(args.url, api.rawConfig));
} else {
console.log('Loaded configuration file "' + api.relativeConfigFile() + '".');
helpers.view.log('Loaded configuration file "' + api.relativeConfigFile() + '".');
}

if (api.rawConfig[env]) {
console.log('Using environment "' + env + '".');
helpers.view.log('Using environment "' + env + '".');

api.rawConfig = api.rawConfig[env];
}
Expand Down

0 comments on commit 5633648

Please sign in to comment.