All files manifest.js

96.88% Statements 31/32
100% Branches 6/6
87.5% Functions 7/8
96.88% Lines 31/32
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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 762x   2x 14x 14x 14x 14x 14x     2x 14x 7x     7x 7x     2x 17x   17x 7x     17x 17x                   2x 10x   10x                 2x 8x                   2x 3x 1x     2x   2x     2x 10x     2x  
const path = require('path');
 
const Manifest = function(fs, date, manifestPath, validity) {
  this.fs = fs;
  this.date = date;
  this.manifestPath = manifestPath;
  this.validity = validity;
  this.manifest = this.open(manifestPath);
}
 
Manifest.prototype.open = function() {
  if (this.fs.existsSync(this.manifestPath)) {
    return JSON.parse(this.fs.readFileSync(this.manifestPath));
  }
 
  this.write({});
  return {};
}
 
Manifest.prototype.write = function(manifest) {
  const dirname = path.dirname(this.manifestPath)
 
  if (!this.fs.existsSync(dirname)) {
    this.fs.mkdirSync(dirname);
  }
 
  const manifestToWrite = JSON.stringify(manifest);
  this.fs.writeFile(this.manifestPath, manifestToWrite)
    .catch(error => console.error(error));
}
 
/**
 * Add an entry to the manifest.
 *
 * @param {String} path
 * @param {Number} expirationDate
 */
Manifest.prototype.add = function(path) {
  this.manifest[path] = this.calculateValidity();
 
  this.write(this.manifest);
}
 
/**
 * Returns if the path exists in the manifest.
 *
 * @param  {String} path
 * @return {Boolean}
 */
Manifest.prototype.exists = function(path) {
  return (path in this.manifest);
}
 
/**
 * Returns if the snapshot is still valid.
 * If the path does not exist in the manifest, it returns false.
 *
 * @param  {String} path
 * @return {Boolean}
 */
Manifest.prototype.isValid = function(path) {
  if (!this.exists(path)) {
    return false;
  }
 
  const expirationDate = this.manifest[path];
 
  return this.date.now() < expirationDate;
}
 
Manifest.prototype.calculateValidity = function(validity) {
  return this.date.now() + (this.validity * 60 * 1000);
}
 
module.exports = Manifest;