Code coverage report for lib/lua/index.js

Statements: 96.97% (32 / 33)      Branches: 87.5% (7 / 8)      Functions: 100% (7 / 7)      Lines: 96.97% (32 / 33)      Ignored: 1 statement, 1 branch     

All files » lib/lua/ » index.js
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 591 1 1 1   1 1 1 1   1 1   4   3 3 3 3 3   1     1 70 67     3 1     3 3 3       3 9   9 1 9     9           1          
var fs = require('fs');
var crypto = require('crypto');
var path = require('path');
var barrier = require('../helpers').barrier;
 
var scripts = {};
var shas = {};
var scriptsRead = false;
var cachedServers = {};
 
var readScripts = function () {
  fs.readdirSync(__dirname)
    .filter(function (file) {
      return file.slice(-4) === '.lua';
    }).forEach(function (file) {
      var hash = crypto.createHash('sha1');
      var key = file.slice(0, -4);
      scripts[key] = fs.readFileSync(path.join(__dirname, file)).toString();
      hash.update(scripts[key]);
      shas[key] = hash.digest('hex');
    });
  scriptsRead = true;
};
 
var buildCache = function (serverKey, client, cb) {
  if (cachedServers[serverKey]) {
    return cb();
  }
 
  if (!scriptsRead) {
    readScripts();
  }
 
  var reportLoaded = barrier(Object.keys(shas).length, function () {
    cachedServers[serverKey] = true;
    return cb();
  });
 
  // todo: could theoretically pipeline this, but it's pretty insignificant
  Object.keys(shas).forEach(function (key) {
    client.script('exists', shas[key], function (err, exists) {
      /* istanbul ignore if */
      Iif (err) {
        client.emit('error', 'Could not build Lua script cache');
      } else Iif (exists[0] === 0) {
        client.script('load', scripts[key], reportLoaded);
      } else {
        reportLoaded();
      }
    });
  });
};
 
module.exports = {
  scripts: scripts,
  shas: shas,
  buildCache: buildCache
};