All files persistence.js

58.33% Statements 21/36
33.33% Branches 4/12
66.67% Functions 6/9
58.33% Lines 21/36
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 76 77 78 79 80 81 82 83 84 85 86 87 88 892x 2x         2x     2x       2x 2x 2x       3x   1x 1x     2x     2x   2x                           2x   2x   2x 2x                         2x   2x 2x                                       2x      
const fs = require('fs');
const path = require('path');
 
// Returns a temporary file
// Example: for /some/file will return /some/.~file
function getTempFile(file) {
  return path.join(path.dirname(file), `.~${path.basename(file)}`);
}
 
const _writeFile = Symbol('writeFile');
 
class Persistence {
  constructor(file) {
    this.file = file;
    this.dataQueue = [];
    this.lock = false;
  }
 
  write(data) {
    if (this.lock) {
      // File is locked - save data for later
      this.dataQueue.push(data);
      return;
    }
 
    const toWrite = this.dataQueue.length ? this.dataQueue[0] : data;
 
    // File is not locked - lock it
    this.lock = true;
 
    this[_writeFile](this.file, toWrite).then(() => {
      // Remove the data from the queue
      this.dataQueue.shift();
 
      // Unlock file
      this.lock = false;
 
      if (this.dataQueue.length) {
        this.write(this.dataQueue[0]);
      }
    });
  }
 
  remove() {
    console.log('removing collection from persistence');
 
    Eif (this.lock) {
      // File is locked - save data for later
      console.log('file is currently being written to');
      return;
    }
 
    // File is not locked - lock it
    this.lock = true;
 
    fs.unlinkSync(this.file);
 
    this.lock = false;
  }
 
  [_writeFile](file, data) {
    // Write data to a temporary file
    const tmpFile = getTempFile(this.file);
 
    return new Promise(resolve => {
      fs.writeFile(tmpFile, data, (writeErr) => {
        if (writeErr) {
          console.log('There was a write error:', writeErr);
          return;
        }
 
        // On success rename the temporary file to the real file
        fs.rename(tmpFile, this.file, (renameErr) => {
          if (renameErr) {
            console.log('There was a rename error:', renameErr);
            return;
          }
 
          resolve();
        });
      });
    });
  }
}
 
module.exports = {
  Persistence
};