Last active
August 29, 2015 14:13
-
-
Save mtomcal/1566d83de97de32e5589 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Earlier | |
var B = require('bluebird'); | |
//Later | |
/** | |
* Promise wrapper for fs.watch | |
* @param path | |
* @returns {*} | |
*/ | |
function fsWatchAsync(path) { | |
var deferred = B.defer(); | |
fs.watch(path, function (event, filename) { | |
deferred.resolve(event, filename); | |
}); | |
return deferred.promise; | |
} | |
/** | |
* Promise wrapper for fs.exists | |
* @param path | |
* @returns {*} | |
*/ | |
function fsExistsAsync(path) { | |
var deferred = B.defer(); | |
fs.exists(path, function (exists) { | |
deferred.resolve(exists); | |
}); | |
return deferred.promise; | |
} | |
/** | |
* Watch a folder for a migration file, read it, run a function based on its | |
* contents then rename the file to a date dot json. | |
*/ | |
function migrationWatcher(children) { | |
var migration_folder = path.join(__dirname, '/migrations/'); | |
var migration_filename = 'migration.json'; | |
var migration_path = path.join(migration_folder, migration_filename) | |
fsWatchAsync(migration_folder) | |
.then(function (event, filename) { //Wait for any file event in folder | |
var results = []; | |
if (filename === migration_filename) { | |
results.push(fsExistsAsync(migration_path)); //Queue a check migration.js exists job | |
} | |
return B.all(results); | |
}) | |
.filter(function (item) { //Only continue pipeline if file exists | |
return item === true; | |
}) | |
.then(function () { | |
return fs.readFileAsync(migration_path); //Read file | |
}) | |
.then(function (file) { | |
var migration = JSON.parse(file); //Parse file | |
var completed_migration = path.join(__dirname, '/migrations/', (new Date()).toJSON() + '.json'); //Rename migration.js to {date}.json | |
processMigration(children, migration); | |
return fs.renameAsync(migration_path, completed_migration); | |
}) | |
.error(function () { | |
console.error("[Migration] Couldnt move migration.json to a dated filename"); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment