Skip to content

Instantly share code, notes, and snippets.

@sacarino
Last active December 19, 2018 18:41
Show Gist options
  • Save sacarino/0e124ca68c120d529487563afe29f901 to your computer and use it in GitHub Desktop.
Save sacarino/0e124ca68c120d529487563afe29f901 to your computer and use it in GitHub Desktop.
Loopback v3.x boot script to automatically update schemas for any datasources that have models connected to them.
'use strict';
const debug = require('debug')('custom:boot:schema-update');
/* Name: 0-schema-update.js
* Purpose: Automatically updates all data sources to match current model definitions
* Warnings: ds.autoupdate does a diff and updates table schemas so it's a non-destructive
* change, but if you remove a property/column then data will be lost!!!
* See more: https: //loopback.io/doc/en/lb3/Creating-a-database-schema-from-models.html#auto-update
*/
function checkSchema(ds, dsName, cb) {
debug(`Checking the ${dsName} schema`);
ds.isActual(function(err, actual) {
if (err) return debug(err);
if (actual) {
// schema is current, we bail
debug(`datasource ${dsName} is up to date`);
} else {
// schema needs to be updated
ds.autoupdate(function(err) {
if (err) return debug(err);
debug(`datasource ${dsName} updated`);
});
}
});
}
// synchronous boot script
module.exports = function(app) {
// for some reason, loopback returns a Title case and lowercase name for the same datasource
// so we're going to .filter that noise out so SQLs don't get executed twice
const sources = Object.keys(app.dataSources);
const datasources = sources.filter(function(item, index) {
return sources.indexOf(item.toLowerCase()) >= index;
});
debug(datasources);
datasources.forEach(dsName => {
const ds = app.dataSources[dsName];
// if we're not connected yet, we wait for the ds connected event to occur
// to prevent bogus EventEmitter memory leak warnings in the console.
// see more: https://github.com/strongloop/loopback/issues/1186
if (ds.connected) {
checkSchema(ds, dsName);
} else {
ds.once('connected', () => {
checkSchema(ds, dsName);
});
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment