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

96.43% Statements 27/28
75% Branches 9/12
100% Functions 6/6
96.43% Lines 27/28
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    3x                   33x         33x           53x           207x           10x   18x   7x     3x           210x   19909x   3x   9x   6x     3x   6x   6x             3x     207x 207x           208x   207x 207x   207x   207x     1x         3x  
"use strict";
 
const Storage = require('./Storage');
 
/**
 * Use an array object as storage.
 * 
 */
class MemoryStorage extends Storage
{
  constructor(options)
  {
    super(options)
 
    /**
     * shared array
     */
    this.array = options.array || [];
  }
 
  /** @override */
  async readAllRecords()
  {
    return JSON.parse(JSON.stringify(this.array));
  }
 
  /** @override */
  createRecord(record)
  {
    return this.updateRecord(record);
  }
 
  /** @override */
  async readRecord(record)
  {
    for (let item of this.array)
    {
      if (item[this.primaryKey] === record[this.primaryKey])
      {
        return JSON.parse(JSON.stringify(item));
      }
    }
    throw new Error('not found');
  }
 
  /** @override */
  async updateRecord(record)
  {
    for (let item of this.array)
    {
      if (item[this.primaryKey] === record[this.primaryKey])
      {
        for (let field in item)
        {
          if (record[field] === undefined)
          {
            delete item[field];
          }
        }
        for (let field in record)
        {
          Eif (record[field] !== undefined)
          {
            item[field] = JSON.parse(JSON.stringify(record[field]));
          }
          else
          {
            delete item[field];
          }
        }
        return JSON.parse(JSON.stringify(item));
      }
    }
    this.array.push(record);
    return record;
  }
 
  /** @override */
  async deleteRecord(record)
  {
    for (let index = 0; index < this.array.length; index++)
    {
      let item = this.array[index]
      Eif (item[this.primaryKey] === record[this.primaryKey])
      {
        this.array.splice(index, 1);
 
        return record;
      }
    }
    throw new Error('not found');
  }
 
}
 
module.exports = MemoryStorage;