|
2 | 2 | function createSmqRpc(smq) {
|
3 | 3 | let idCounter=0;
|
4 | 4 | let callbacks={} // saved RPC callbacks: key=id, val=promise
|
5 |
| - smq.subscribe("self", "$RpcResp", {datatype:"json",onmsg:(pl) => { |
6 |
| - let promise=callbacks[pl.id]; |
7 |
| - if(promise) { |
8 |
| - delete callbacks[pl.id]; // Release |
9 |
| - if(pl.err) promise.reject(new Error(pl.err)); |
10 |
| - else promise.resolve(pl.rsp); |
11 |
| - } |
12 |
| - else { |
13 |
| - console.error(`SMQ RPC: promise (callback) not found for id '${pl.id}'`); |
14 |
| - } |
15 |
| - }}); |
| 5 | + let subscribed=false; |
| 6 | + function subscribe() { |
| 7 | + smq.subscribe("self", "$RpcResp", {datatype:"json",onmsg:(pl) => { |
| 8 | + let promise=callbacks[pl.id]; |
| 9 | + if(promise) { |
| 10 | + delete callbacks[pl.id]; // Release |
| 11 | + if(pl.err) promise.reject(new Error(pl.err)); |
| 12 | + else promise.resolve(pl.rsp); |
| 13 | + } |
| 14 | + else { |
| 15 | + console.error(`SMQ RPC: promise (callback) not found for id '${pl.id}'`); |
| 16 | + } |
| 17 | + }}); |
| 18 | + }; |
16 | 19 | return {
|
17 |
| - proxy: new Proxy({}, { |
18 |
| - get(target, prop, receiver) { |
19 |
| - // Return a function that, when called, returns a Promise |
20 |
| - return (...args) => { |
21 |
| - return new Promise((resolve, reject) => { |
22 |
| - // Assemble payload |
23 |
| - const pl = { |
24 |
| - id: ++idCounter, |
25 |
| - name: prop, |
26 |
| - args: args |
27 |
| - }; |
28 |
| - callbacks[idCounter]={resolve:resolve,reject:reject}; |
29 |
| - smq.pubjson(pl, 1, "$RpcReq"); // Publish to etid 1, the server. |
30 |
| - }); |
31 |
| - }; |
32 |
| - } |
33 |
| - }), |
34 |
| - disconnect: function(report) { |
35 |
| - if(false != report) { |
36 |
| - for(let id in callbacks) { |
37 |
| - let promise=callbacks[id]; |
38 |
| - promise.reject("disconnected"); |
39 |
| - } |
40 |
| - } |
41 |
| - callbacks={}; |
42 |
| - } |
| 20 | + proxy: new Proxy({}, { |
| 21 | + get(target, prop, receiver) { |
| 22 | + // Return a function that, when called, returns a Promise |
| 23 | + if( ! subscribed ) { |
| 24 | + subscribe(); |
| 25 | + subscribed=true; |
| 26 | + }; |
| 27 | + return (...args) => { |
| 28 | + return new Promise((resolve, reject) => { |
| 29 | + // Assemble payload |
| 30 | + const pl = { |
| 31 | + id: ++idCounter, |
| 32 | + name: prop, |
| 33 | + args: args |
| 34 | + }; |
| 35 | + callbacks[idCounter]={resolve:resolve,reject:reject}; |
| 36 | + smq.pubjson(pl, 1, "$RpcReq"); // Publish to etid 1, the server. |
| 37 | + }); |
| 38 | + }; |
| 39 | + } |
| 40 | + }), |
| 41 | + disconnect: function(report) { |
| 42 | + if(false != report) { |
| 43 | + for(let id in callbacks) { |
| 44 | + let promise=callbacks[id]; |
| 45 | + promise.reject("disconnected"); |
| 46 | + } |
| 47 | + } |
| 48 | + callbacks={}; |
| 49 | + subscribed=false; |
| 50 | + } |
43 | 51 | };
|
44 | 52 | };
|
0 commit comments