2018-03-26 20:23:34 +00:00
|
|
|
/* eslint-env browser */
|
|
|
|
|
2018-03-26 19:17:19 +00:00
|
|
|
const isFunction = require('lodash/isFunction');
|
|
|
|
const isObject = require('lodash/isObject');
|
|
|
|
const isString = require('lodash/isString');
|
2018-03-28 17:05:49 +00:00
|
|
|
const head = require('lodash/head');
|
|
|
|
const last = require('lodash/last');
|
2018-03-26 19:17:19 +00:00
|
|
|
|
2018-03-26 19:34:36 +00:00
|
|
|
const { deferredToPromise } = require('../deferred_to_promise');
|
2018-03-26 19:17:19 +00:00
|
|
|
|
2018-03-26 19:34:36 +00:00
|
|
|
|
2018-03-28 17:00:52 +00:00
|
|
|
const closeDatabaseConnection = ({ Backbone } = {}) =>
|
2018-03-28 14:54:01 +00:00
|
|
|
deferredToPromise(Backbone.sync('closeall'));
|
2018-03-26 20:23:34 +00:00
|
|
|
|
|
|
|
exports.runMigrations = async ({ Backbone, database } = {}) => {
|
2018-03-26 19:17:19 +00:00
|
|
|
if (!isObject(Backbone) || !isObject(Backbone.Collection) ||
|
|
|
|
!isFunction(Backbone.Collection.extend)) {
|
|
|
|
throw new TypeError('"Backbone" is required');
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!isObject(database) || !isString(database.id) ||
|
|
|
|
!Array.isArray(database.migrations)) {
|
|
|
|
throw new TypeError('"database" is required');
|
|
|
|
}
|
|
|
|
|
|
|
|
const migrationCollection = new (Backbone.Collection.extend({
|
|
|
|
database,
|
|
|
|
storeName: 'items',
|
|
|
|
}))();
|
|
|
|
|
2018-03-26 23:11:21 +00:00
|
|
|
await deferredToPromise(migrationCollection.fetch({ limit: 1 }));
|
2018-03-28 14:38:05 +00:00
|
|
|
console.log('Close database connection');
|
2018-03-28 17:00:52 +00:00
|
|
|
await closeDatabaseConnection({ Backbone });
|
2018-03-26 19:17:19 +00:00
|
|
|
};
|
2018-03-28 17:05:49 +00:00
|
|
|
|
|
|
|
const getMigrationVersions = (database) => {
|
|
|
|
if (!isObject(database) || !Array.isArray(database.migrations)) {
|
|
|
|
throw new TypeError('"database" is required');
|
|
|
|
}
|
|
|
|
|
|
|
|
const firstMigration = head(database.migrations);
|
|
|
|
const lastMigration = last(database.migrations);
|
|
|
|
|
|
|
|
const firstVersion = firstMigration ? parseInt(firstMigration.version, 10) : null;
|
|
|
|
const lastVersion = lastMigration ? parseInt(lastMigration.version, 10) : null;
|
|
|
|
|
|
|
|
return { firstVersion, lastVersion };
|
|
|
|
};
|