All files / lib/plugins/stores memory-store.ts

95.24% Statements 20/21
100% Branches 7/7
85.71% Functions 6/7
94.74% Lines 18/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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    4x 4x 4x                       4x       10x                 4x 15x                     4x 7x 7x                   4x 2x 2x 2x               4x 4x   4x   4x              
"use strict";
 
import _get from "lodash/get";
import _set from "lodash/set";
import _unset from "lodash/unset";
 
import { Store } from "./types";
 
export type PropertyMeta = {
  propertyPath: string;
};
 
export type MemoryStoreArgs = { data: Data };
 
type Data = { [key: string]: unknown };
 
export class MemoryStore implements Store {
  data: Data;
 
  constructor(args?: MemoryStoreArgs) {
    this.data = args?.data || {};
  }
  /**
   * get a property from the store
   *
   * @param {Object} prop - property metadata
   * @param {String} prop.propertyPath - the path to the property
   * @returns {Promise} property value
   */
  async get(prop: PropertyMeta) {
    return _get(this.data, prop.propertyPath);
  }
 
  /**
   * set a property in the store
   *
   * @param {Object} prop - property metadata
   * @param {String} prop.propertyPath - the path to the property
   * @param {*} value - The value to set on the property.
   * @returns {Promise} property value
   */
  async set(prop: PropertyMeta, value: unknown) {
    _set(this.data, prop.propertyPath, value);
    return value;
  }
 
  /**
   * delete a property from the store
   *
   * @param {Object} prop - property metadata
   * @param {String} prop.propertyPath - the path to the property
   * @returns {Promise} previous property value
   */
  async delete(prop: PropertyMeta) {
    const value = await this.get(prop);
    _unset(this.data, prop.propertyPath);
    return value;
  }
 
  /**
   * read the store data
   *
   * @returns {Object} the store data
   */
  read() {
    return JSON.parse(JSON.stringify(this.data));
  }
}
 
export function plugin(args: MemoryStoreArgs) {
  return {
    stores: {
      session: new MemoryStore(args)
    }
  };
}