generated from cap-js-community/repository-template
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathComponent.js
More file actions
82 lines (78 loc) · 2.5 KB
/
Component.js
File metadata and controls
82 lines (78 loc) · 2.5 KB
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
"use strict";
sap.ui.define(
["sap/fe/core/AppComponent", "sap/ui/core/ws/WebSocket", "sap/ui/core/ws/ReadyState"],
function (AppComponent, WebSocket, ReadyState) {
const KEEP_ALIVE_INTERVAL = 60 * 1000; // 1 minute
return AppComponent.extend("todo.Component", {
metadata: {
manifest: "json",
},
constructor: function () {
AppComponent.prototype.constructor.apply(this, arguments);
this.websocket("/ws/todo");
},
websocket: function (sUrl, sName = "main") {
window.websockets ??= {};
window.websockets[sName] = {
_ws: undefined,
_contexts: [],
_handlers: [],
_interval: setInterval(() => {
window.websockets?.[sName]?.init();
}, KEEP_ALIVE_INTERVAL),
reset: function () {
this._ws?.close();
this._ws = undefined;
this._contexts = [];
this._handlers = [];
},
init: function () {
if (this._ws?.getReadyState() === ReadyState.OPEN) {
return;
}
this._ws = new WebSocket(sUrl);
this._ws.attachClose((oEvent) => {
if (oEvent.getSource() === this._ws) {
this._ws = undefined;
}
});
this._ws.attachError((oEvent) => {
if (oEvent.getSource() === this._ws) {
this._ws = undefined;
}
});
for (const fnCallback of this._handlers) {
this._attach(fnCallback);
}
for (const oContext of this._contexts) {
this._send(oContext);
}
},
send: function (oMessage) {
this.init();
this._send(oMessage);
if (oMessage.event === "wsContext") {
this._contexts.push(oMessage);
}
},
message: function (fnCallback) {
this.init();
this._attach(fnCallback);
this._handlers.push(fnCallback);
},
_send: function (oData) {
this._ws.send(JSON.stringify(oData));
},
_attach: function (fnCallback) {
this._ws.attachMessage("message", (oEvent) => {
const oMessage = JSON.parse(oEvent.getParameter("data"));
fnCallback(oMessage, oEvent);
});
},
};
window.websockets[sName].reset();
window.websockets[sName].init();
},
});
},
);