All files / node-collections-boilerplate-nahid/storage FSStorage.js

100% Statements 68/68
83.33% Branches 10/12
100% Functions 11/11
100% Lines 68/68
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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177    1x 1x   1x                           19x       19x 19x   19x   1x                   19x                 34x 34x   206x   206x 206x   206x       34x           24x 24x   407x 407x 407x   24x           205x           409x   409x 409x   409x       1x               206x   206x 206x 206x 206x 206x 206x             206x   206x 206x 206x 205x 205x             15x 15x 15x 15x     15x 15x   2x   1x 1x 1x 1x       15x 15x   204x   203x 203x 203x 203x         15x 15x   204x   1x 1x 1x 1x     15x         1x  
"use strict";
 
const fs = require('fs');
const path = require('path');
 
const Storage = require('./Storage');
 
/**
 * Collection served from file system storage.
 * 
 * Very useful for rapid prototyping.
 */
class FSStorage extends Storage
{
  /**
   * @param {StorageOptions} options see fields
   */
  constructor(options)
  {
    super(options)
    /**
     * folder path where data is kept
     */
    this.dirname = options.connectionString;
    try
    {
      if (!fs.existsSync(this.dirname))
      {
        fs.mkdirSync(this.dirname);
      }
    }
    catch (e)
    {
 
    }
    /**
     * Mapping between id and last modified data.
     */
    this.list = this.listItems();
  }
 
  /**
   * Return a mapping between record id and last modified data at directory.
   * Used for update checking.
   */
  listItems()
  {
    let output = {};
    for (let file of fs.readdirSync(this.dirname))
    {
      Eif (file.match(/\.json$/))
      {
        let stat = fs.statSync(path.join(this.dirname, file));
        Eif (stat.isFile())
        {
          output[file.substr(0, file.length - 5)] = stat.mtime;
        }
      }
    }
    return output;
  }
 
  /** @override  */
  readAllRecords()
  {
    let output = [];
    for (let key in this.list)
    {
      let query = {};
      query[this.primaryKey] = key;
      output.push(this.readRecord(query));
    }
    return Promise.all(output);
  }
 
  /** @override  */
  createRecord(record)
  {
    return this.updateRecord(record);
  }
 
  /** @override  */
  readRecord(record)
  {
    return new Promise((resolve, reject) =>
    {
      let key = record[this.primaryKey];
      try
      {
        resolve(JSON.parse(fs.readFileSync(path.join(this.dirname, key + '.json'))));
      }
      catch (e)
      {
        reject(e);
      }
    });
  }
 
  /** @override  */
  updateRecord(record)
  {
    return new Promise((resolve, reject) =>
    {
      let key = record[this.primaryKey];
      let file = path.join(this.dirname, key + '.json');
      fs.writeFileSync(file, JSON.stringify(record, null, 1));
      let stat = fs.statSync(file);
      this.list[key] = stat.mtime;
      resolve(JSON.parse(fs.readFileSync(file)));
    });
  }
 
  /** @override  */
  deleteRecord(record)
  {
    return new Promise((resolve, reject) =>
    {
      let key = record[this.primaryKey];
      let file = path.join(this.dirname, key + '.json');
      fs.unlinkSync(file);
      delete this.list[key];
      resolve(record);
    });
  }
 
  /** @override  */
  async updateCheckImpl()
  {
    let updated = false;
    let newlist = this.listItems(),
      list = this.list,
      type, record = {};
 
    // check for deleted item
    type = 'delete';
    for (let item in list)
    {
      if (!newlist[item])
      {
        record[this.primaryKey] = item;
        this.emit(type, record);
        delete list[item];
        updated = true;
      }
    }
    // check for new items
    type = 'create';
    for (let item in newlist)
    {
      if (!list[item])
      {
        record = JSON.parse(fs.readFileSync(path.join(this.dirname, item + '.json')));
        this.emit(type, record);
        list[item] = newlist[item];
        updated = true;
      }
    }
 
    // check for modified items
    type = 'update';
    for (let item in list)
    {
      if (list[item].getTime() !== newlist[item].getTime())
      {
        record = JSON.parse(fs.readFileSync(path.join(this.dirname, item + '.json')));
        this.emit(type, record);
        list[item] = newlist[item];
        updated = true;
      }
    }
    return updated;
  }
 
}
 
module.exports = FSStorage;