/
ngs.html
79 lines (68 loc) · 2.27 KB
/
ngs.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
crossorigin="anonymous">
</head>
<body>
<!-- a place to record messages -->
<div id="messages" class="container"></div>
<!-- load a script -->
<script type="module">
import { connect, StringCodec, credsAuthenticator } from '../esm/nats.js'
// add an entry to the document
function addEntry (s) {
const p = document.createElement('pre')
p.appendChild(document.createTextNode(s))
document.getElementById('messages').appendChild(p)
}
const sc = StringCodec()
async function testConnection (nc) {
addEntry('connected to NATS!')
// simple publisher
nc.publish('hello', sc.encode('nats'))
addEntry('published a message to `hello`')
// simple subscriber, if the message has a reply subject
// send a reply
const sub = await nc.subscribe('help');
(async () => {
addEntry('listening for request on `help`')
for await (const m of sub) {
m.respond(sc.encode(`I can help ${sc.decode(m.data)}`))
}
})().then()
// request data - requests only receive one message
// to receive multiple messages, create a subscription
addEntry('making a request to `help`')
const msg = await nc.request('help', sc.encode('nats request'))
addEntry(`got response '${sc.decode(msg.data)}'`)
// close the connection
nc.close()
addEntry('closed the connection')
}
async function init () {
// To connect to NGS you need a creds or jwt authenticator
// you can create one with nsc:
// nsc add operator -u synadia
// nsc add account myaccount
// nsc add user myuser
// nsc generate creds -a myaccount -n myuser -o ./myuser.creds
// fetch the creds
const creds = await fetch('./myuser.creds')
if (!creds.ok) {
addEntry("unable to find ./myuser.creds - aborting")
return;
}
const token = await creds.text()
const auth = credsAuthenticator(sc.encode(token))
// connect
let nc = await connect({ servers: 'wss://connect.ngs.global', authenticator: auth, debug: true })
await testConnection(nc)
await nc.closed
}
init()
</script>
</body>
</html>