summaryrefslogtreecommitdiff
path: root/WebInterface/NodeJSServer/src/js/modules/interface.js
blob: ac5ea934b83d4a687c25dbcf5bb6217aa3e3332a (plain)
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
/**
 * Stores an object and it's public methods
 */
class InterfaceAccessor {
  /**
   * Creates new accessor for object with publicMethods being exposed
   * @param {object} object
   * @param {array<String>} publicMethods
   */
  constructor(object, publicMethods) {
    this.object = object;
    this.publicMethods = publicMethods;
  }

  /**
   * Executes method if it is a public method
   * @param {string} method Name of method to call
   * @return {number} 0 success, 1 method not public, 2 method not found
   */
  execute(method, ...args) {
    if (!this.publicMethods.includes(method)) return 1;
    if (typeof this.object[method] != 'function') return 2;

    this.object[method](...args);
    return 0;
  }
}

/**
 * Implements communication between objects
 */
export default class Interface {
  /**
   * Initializes interface
   */
  constructor() {
    this.objects = {};
  }

  /**
   * Adds a new object to array at objKey and assigns public methods
   * @param {object} object Object to reference in Interface
   * @param {String} objKey Key to reference the object under
   * @param {Array} publicMethods Names of public methods
   */
  addObject(object, objKey, publicMethods) {
    if (!this.objects[objKey]) this.objects[objKey] = [];
    this.objects[objKey].push(new InterfaceAccessor(object, publicMethods));
  }

  /**
   * Unregisters object
   * @param {Object} object
   * @param {String} objKey
   */
  removeObject(object, objKey) {
    if (!this.objects[objKey]) return;

    // Remove all instances of object from objKey
    objects[objKey] = objects[objKey].filter(elt => elt.object != object);

    // Remove reference, if none remain
    if (objects[objKey].length == 0) objects[objKey] = undefined;
  }

  /**
   * Calls a method on all objects with the key objKey
   * @param {String} objKey Object Key of objects to call method on
   * @param {String} method Method name to call on the objects
   * @param {...*} args Arguments to pass
   * @return {number} 0 Success, 1 no objects with objKey, 2 method not public
   */
  callMethod(objKey, method, ...args) {
    if (!this.objects[objKey]) return 1;

    let returnCode = 0;
    for (let obj of this.objects[objKey]) {
      if (obj.execute(method, ...args) != 0) returnCode = 2;
    }
    return returnCode;
  }
}