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

84.06% Statements 58/69
85.71% Branches 24/28
72.73% Functions 8/11
84.06% Lines 58/69
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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234    9x   9x 9x 9x                         129x         129x       129x       129x 129x 129x   110x           129x         129x         129x                                                 1x                               1x               1x                   61x                                                     61x                         45x   27x       27x     45x 45x 45x 45x 45x 45x   612x     45x   27x 27x       18x 18x   6x   3x 3x 3x 3x         18x 18x   612x   609x 609x 609x 609x         18x 18x   612x   3x 3x 3x 3x     18x                 54x   48x 48x           9x  
"use strict";
 
const EventEmitter = require('events');
 
const ONE_MINUTE_MS = 60 * 1000
const FIFTEEN_MINUTES_MS = 15 * 60 * 1000;
const ONE_PERCENT_RATIO = 1.01;
 
/**
 * @abstract
 * @public
 */
class Storage extends EventEmitter
{
  /**
   * @param {StorageOptions} options see fields
   */
  constructor(options)
  {
    super();
 
    /**
     * id field of record
     */
    this.primaryKey = options.primaryKey || 'id';
    /**
     * Connection string for storage. e.g. for FSStorage, it is a path
     */
    this.connectionString = options.connectionString || '';
    /**
     * Name of collection. Derived from connection string if there is # based seperation.
     */
    this.collectionName = this.connectionString.substr(this.connectionString.indexOf('#') + 1);
    this.connectionString = this.connectionString.substr(0, this.connectionString.indexOf('#'));
    if (!this.connectionString)
    {
      delete this.connectionString;
    }
    /**
     * Minimum duration between updates in ms
     * @type {number}
     */
    this.updateInterval = options.updateInterval || ONE_MINUTE_MS;
    /**
     * Maximum duration between updates in ms
     * @type {number}
     */
    this.updateIntervalMax = options.updateIntervalMax || FIFTEEN_MINUTES_MS;
    /**
     * Rate at which update checks are slowed down when there are no updates.
     * @type {number}
     */
    this.updateIntervalSlowdownRate = options.updateIntervalSlowdownRate || ONE_PERCENT_RATIO;
  }
 
  /**
   * Connect to data storage
   */
  async connect()
  {
 
  }
 
  /**
   * @return {Array<Record>}
   * @abstract
   */
  async readAllRecords()
  {
    throw new Error('TODO: not immplemented');
  }
 
  /**
   * @abstract
   */
  async createRecord(record)
  {
    throw new Error('TODO: not immplemented');
  }
 
  /**
   * @abstract
   */
  async readRecord(record)
  {
    throw new Error('TODO: not immplemented');
  }
 
  /**
   * @abstract
   */
  async updateRecord(record)
  {
    throw new Error('TODO: not immplemented');
  }
 
  /**
   * @abstract
   */
  async deleteRecord(record)
  {
    throw new Error('TODO: not immplemented');
  }
 
  /**
   * Start checking for updates.
   * Emit events when there are updates.
   * Required for use with CachedCollection
   */
  startRecordUpdateCheck()
  {
    let currentTimeout = this.updateInterval;
    async function checkUpdate()
    {
      /**
       * update check timeout object
       */
      this.timeout = undefined;
      let updated = false;
      try
      {
        updated = await this.updateCheckImpl();
      }
      catch (e)
      {
        console.error(e);
      }
      if (updated || !this.updateIntervalSlowdownRate)
      {
        currentTimeout = this.updateInterval;
      }
      else
      {
        currentTimeout = Math.min(currentTimeout * this.updateIntervalSlowdownRate, this.updateIntervalMax);
      }
      this.timeout = setTimeout(checkUpdate.bind(this), currentTimeout)
        .unref();
    }
    this.timeout = setTimeout(checkUpdate.bind(this), currentTimeout)
      .unref();
  }
 
  /**
   * Implmentation of update checking.
   *
   * Override this if storage has more efficient way of checking for updates.
   *
   * @abstract
   */
  async updateCheckImpl()
  {
    if (!this.bruteForceNotified)
    {
      console.log('WARNING: UPDATE IS NOT NATIVELY SUPPORTED BY STORAGE; USING BRUTE FORCE UPDATE. THIS MAY BE SLOWER AND LEAD TO GREATER BANDWIDTH USAGE.');
      /**
       * if there are no efficient way of checking update, make a warning notification once
       */
      this.bruteForceNotified = true;
    }
 
    let updated = false;
    let records = await this.readAllRecords();
    let newlist = {},
      type, record = {},
      list = this.lookup;
    for (let record of records)
    {
      newlist[record[this.primaryKey]] = record;
    }
 
    if (!list)
    {
      this.lookup = newlist;
      return false;
    }
 
    // check for deleted item
    type = 'delete';
    for (let item in list)
    {
      if (!newlist[item])
      {
        record[this.primaryKey] = item;
        this.emit(type, record);
        delete list[record[this.primaryKey]];
        updated = true;
      }
    }
 
    // check for new items
    type = 'create';
    for (let item in newlist)
    {
      if (!list[item])
      {
        record = newlist[item];
        this.emit(type, record);
        updated = true;
        list[record[this.primaryKey]] = record;
      }
    }
 
    // check for modified items
    type = 'update';
    for (let item in list)
    {
      if (JSON.stringify(list[item]) !== JSON.stringify(newlist[item]))
      {
        record = newlist[item];
        this.emit(type, record);
        updated = true;
        list[record[this.primaryKey]] = record;
      }
    }
    return updated;
  }
 
  /**
   * Stop checking for updates.
   * Required for use with CachedCollection
   */
  stopRecordUpdateCheck()
  {
    if (this.timeout)
    {
      clearTimeout(this.timeout);
      this.timeout = undefined;
    }
  }
 
}
 
module.exports = Storage;