all files / bull/lib/commands/ index.js

100% Statements 20/20
100% Branches 2/2
100% Functions 8/8
100% Lines 20/20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60                                            112× 108×   108× 1944×               19×     18× 18× 18×   18× 18×              
/**
 * Load redis lua scripts.
 * The name of the script must have the following format:
 *
 * cmdName-numKeys.lua
 *
 * cmdName must be in camel case format.
 *
 * For example:
 * moveToFinish-3.lua
 *
 */
'use strict';
 
var fs = require('fs');
var path = require('path');
var Promise = require('bluebird');
 
var utils = require('../utils');
 
fs = Promise.promisifyAll(fs);
 
//
// for some very strange reason, defining scripts with this code results in this error
// when executing the scripts: ERR value is not an integer or out of range
//
module.exports = (function() {
  var scripts;
 
  return function(client) {
    return utils.isRedisReady(client).then(function() {
      scripts = scripts || loadScripts(__dirname);
 
      return scripts.each(function(command) {
        return client.defineCommand(command.name, command.options);
      });
    });
  };
})();
 
function loadScripts(dir) {
  return fs
    .readdirAsync(dir)
    .filter(function(file) {
      return path.extname(file) === '.lua';
    })
    .map(function(file) {
      var longName = path.basename(file, '.lua');
      var name = longName.split('-')[0];
      var numberOfKeys = parseInt(longName.split('-')[1]);
 
      return fs.readFileAsync(path.join(dir, file)).then(function(lua) {
        return {
          name: name,
          options: { numberOfKeys: numberOfKeys, lua: lua.toString() }
        };
      });
    });
}