@jcbuisson/express-x-client 2.0.1 → 2.0.2

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/package.json +1 -1
  2. package/src/index.mjs +17 -8
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jcbuisson/express-x-client",
3
- "version": "2.0.1",
3
+ "version": "2.0.2",
4
4
  "type": "module",
5
5
  "description": "Client library for ExpressX framework",
6
6
  "main": "src/index.mjs",
package/src/index.mjs CHANGED
@@ -16,6 +16,7 @@ export default function expressXClient(socket, options={}) {
16
16
 
17
17
  const waitingPromisesByUid = {}
18
18
  const action2service2handlers = {}
19
+ const type2appHandler = {}
19
20
  const socketConnectionState = {}
20
21
 
21
22
  socket.on("connect", async () => {
@@ -67,14 +68,6 @@ export default function expressXClient(socket, options={}) {
67
68
  const handler = serviceHandlers[name]
68
69
  if (handler) handler(result)
69
70
  })
70
-
71
- // on receiving application events from pub/sub
72
- socket.on('app-event', ({ type, value }) => {
73
- if (options.debug) console.log('app-event', type, value)
74
- if (!type2appHandlers[type]) type2appHandlers[type] = {}
75
- const handler = type2appHandlers[type]
76
- if (handler) handler(value)
77
- })
78
71
 
79
72
  async function serviceMethodRequest(name, action, options, ...args) {
80
73
  // create a promise which will resolve or reject by an event 'client-response'
@@ -120,10 +113,26 @@ export default function expressXClient(socket, options={}) {
120
113
  return new Proxy(service, handler)
121
114
  }
122
115
 
116
+ /////////////// APPLICATION-LEVEL EVENTS /////////////////
117
+
118
+ // There is a need for events sent outside any service method call, for example on unsolicited-by-frontend backend state change
119
+ socket.on('app-event', ({ type, value }) => {
120
+ if (options.debug) console.log('app-event', type, value)
121
+ if (!type2appHandler[type]) type2appHandler[type] = {}
122
+ const handler = type2appHandler[type]
123
+ if (handler) handler(value)
124
+ })
125
+
126
+ // add application event handler
127
+ function on(type, handler) {
128
+ type2appHandler[type] = handler
129
+ }
130
+
123
131
  return {
124
132
  socketConnection,
125
133
  socketStatus,
126
134
  service,
135
+ on,
127
136
  }
128
137
  }
129
138