-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathws-demo-single-call.html
89 lines (81 loc) · 2.74 KB
/
ws-demo-single-call.html
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
83
84
85
86
87
88
89
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>RIG-WS-Demo</title>
</head>
<body>
<form onsubmit="sendGreeting(); return false;">
<input type="text" id="greeting" placeholder="Your greeting here" autofocus />
<input type="submit" id="submit-button" disabled>
</form>
<ul id="eventList" style="list-style:none;padding-left:0"></ul>
<script>
const eventList = document.getElementById('eventList');
function addEvent(cloudEvent) {
const { eventTime, data } = cloudEvent;
const li = document.createElement('li');
li.textContent = `[${new Date(eventTime).toLocaleTimeString()}] ${data}`;
eventList.appendChild(li);
}
const baseUrl = 'http://localhost:4000/_rig/v1';
const wsUrl = 'ws://localhost:4000/_rig/v1';
function randomString() {
return (
Math.random()
.toString(36)
.substring(2, 15) +
Math.random()
.toString(36)
.substring(2, 15)
);
}
function sendGreeting() {
const input = document.getElementById('greeting');
const greeting = input.value;
input.value = '';
return fetch(`${baseUrl}/events`, {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
body: JSON.stringify({
cloudEventsVersion: '0.1',
eventID: randomString(),
eventType: 'greeting.simple',
eventTime: new Date().toISOString(),
source: 'sse-demo-ui',
contentType: 'text/plain',
data: greeting
})
})
.then(response => response.json())
.then(json => {
console.log('CloudEvent sent:', json);
return json;
})
.catch(err => {
console.log('Failed to send CloudEvent:', err);
});
}
const source = new WebSocket(
`${wsUrl}/connection/ws?subscriptions=[{\"eventType\":\"greeting.simple\"}]`
);
source.onopen = e => console.log('open', e);
source.onmessage = e => {
console.log('message', e);
const cloudEvent = JSON.parse(e.data);
if (cloudEvent.type === 'rig.connection.create') {
payload = cloudEvent.data;
console.log('Subscription created:', payload);
} else if (cloudEvent.eventType === 'greeting.simple') {
addEvent(cloudEvent);
} else if (cloudEvent.type === 'rig.subscriptions_set') {
document.getElementById("submit-button").removeAttribute("disabled");
}
};
source.onerror = e => console.log('error', e);
</script>
</body>
</html>