mongo-realtime 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.js +49 -0
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -4,6 +4,8 @@ class MongoRealtime {
4
4
  /** @type {import("socket.io").Server} */ static io;
5
5
  /** @type {import("mongoose").Connection} */ static connection;
6
6
  /** @type {[import("socket.io").Socket]} */ static sockets = [];
7
+ /** @type {Record<String, [(change:ChangeStreamDocument)=>void]>} */ static #listeners =
8
+ {};
7
9
 
8
10
  /**
9
11
  * Initializes the socket system.
@@ -71,6 +73,8 @@ class MongoRealtime {
71
73
 
72
74
  changeStream.on("change", (change) => {
73
75
  const colName = change.ns.coll.toLowerCase();
76
+ change.col = colName;
77
+
74
78
  const type = change.operationType;
75
79
  const id = change.documentKey?._id;
76
80
 
@@ -87,16 +91,61 @@ class MongoRealtime {
87
91
  ];
88
92
 
89
93
  if (id) {
94
+ change.docId = id;
90
95
  const e_change_doc = `${e_change_col}:${id}`;
91
96
  const e_change_type_doc = `${e_change_type_col}:${id}`;
92
97
  events.push(e_change_doc, e_change_type_doc);
93
98
  }
94
99
  for (let e of events) {
95
100
  this.io.emit(e, change);
101
+ this.notifyListeners(e, change);
96
102
  }
97
103
  });
98
104
  });
99
105
  }
106
+
107
+ /**
108
+ * Notify all event listeners
109
+ *
110
+ * @param {String} e - Name of the event
111
+ * @param {ChangeStreamDocument} change - Change Stream
112
+ */
113
+ static notifyListeners(e, change) {
114
+ if (this.#listeners[e]) {
115
+ for (let c of this.#listeners[e]) {
116
+ c(change);
117
+ }
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Subscribe to an event
123
+ *
124
+ * @param {String} key - Name of the event
125
+ * @param {(change:ChangeStreamDocument)=>void} cb - Callback
126
+ */
127
+ static listen(key, cb) {
128
+ if (!this.#listeners[key]) this.#listeners[key] = [];
129
+ this.#listeners[key].push(cb);
130
+ }
131
+
132
+ /**
133
+ * Remove one or all listeners of an event
134
+ *
135
+ * @param {String} key - Name of the event
136
+ * @param {(change:ChangeStreamDocument)=>void} cb - Callback
137
+ */
138
+ static removeListener(key, cb) {
139
+ if (cb) this.#listeners[key] = this.#listeners[key].filter((c) => c != cb);
140
+ else this.#listeners[key] = [];
141
+ }
142
+
143
+ /**
144
+ * Unsubscribe to all events
145
+ */
146
+ static removeAllListeners() {
147
+ this.#listeners = {};
148
+ }
100
149
  }
101
150
 
102
151
  module.exports = MongoRealtime;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mongo-realtime",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "main": "index.js",
5
5
  "scripts": {},
6
6
  "keywords": [