sails-migrations icon indicating copy to clipboard operation
sails-migrations copied to clipboard

If sails is already loaded, do not load again

Open kmcgrath opened this issue 9 years ago • 11 comments

This allows sails-migrations to be used within sails itself. It checks to see if sails is already loaded. If so, it does not do it again.

Then it is possible use sails-migrations directly to report on status and currentVersion from a Controller.

In the following example I also have the ability to migrate and roll back, but I realize you may not want to do that here, unless bootstrapping an application through a web interface.

/** 
 * MigrateController
 *   
 * @description :: Server-side logic for managing knex migrations
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */  

var vm = require('vm');
var sailsMigrations = require('sails-migrations');

module.exports = { 

  latest: function(req,res,next) {
    return sailsMigrations.migrate()
    .spread(function (batchNo, log) {
      if (log.length === 0) {
        res.json({
          message: 'Already up to date'
        }); 
      }   
      else {
        res.json({
          message: 'Batch ' + batchNo + ' run: ' + log.length,
          migrations: log 
        }); 
      }   
    })  
    .catch(next);
  },  

  rollback: function(req,res,next) {
    return sailsMigrations.rollback()
    .spread(function (batchNo, log) {
      if (log.length === 0) {
        res.json({
          message: 'Already at the base migration'
        }); 
      }   
      else {
        res.json({
          message: 'Batch ' + batchNo + ' rolled back: ' + log.length,
          migrations: log 
        }); 
      }   
    })  
    .catch(next);
  },  

  currentVersion: function(req,res,next) {
    return sailsMigrations.currentVersion()
    .then(function (version) {
      res.json({
        version: version
      }); 
    })  
    .catch(next);
  },  

  status: function(req,res,next) {
    return sailsMigrations.status()
    .spread(function (all,completed) {
      all = all || []; 
      completed = completed || []; 

      res.json({
        all: all,
        completed: completed
      }); 
    })  
    .catch(next);
  }   

};  

kmcgrath avatar Jun 15 '15 19:06 kmcgrath