All files / core store.ts

0% Statements 0/19
0% Branches 0/4
0% Functions 0/6
0% Lines 0/14
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                                                                                             
import { STATEX_ACTION_KEY } from './constance'
 
/**
 * Use reflection library
 */
declare var Reflect: any
 
/**
 * This decorator configure instance of a store
 *
 * @export
 * @param {*} storeClass
 * @returns
 */
export function store() {
 
  return (storeClass: any) => {
    // save a reference to the original constructor
    let original = storeClass
 
    // a utility function to generate instances of a class
    function construct(constructor, args) {
      let dynamicClass: any = function () {
        return new constructor(...args)
      }
      dynamicClass.prototype = constructor.prototype
      return new dynamicClass()
    }
 
    // the new constructor behavior
    let overriddenConstructor: any = function Store(...args) {
      if (!Reflect.hasMetadata(STATEX_ACTION_KEY, this)) return
      let statexActions = Reflect.getMetadata(STATEX_ACTION_KEY, this)
      Object.keys(statexActions).forEach(name => new statexActions[name]().subscribe(this[name], this))
      return construct(original, args)
    }
 
    // copy prototype so instanceof operator still works
    overriddenConstructor.prototype = original.prototype
 
    // create singleton instance
    const instance = new overriddenConstructor()
 
    // return new constructor (will override original)
    return instance && overriddenConstructor
  }
}