-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfrequency-service.ts
57 lines (48 loc) · 1.21 KB
/
frequency-service.ts
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
import { connect, JSONCodec } from "./natslib.ts";
type Badge = {
name: string;
company?: string;
};
const jc = JSONCodec();
const nc = await connect({ servers: "demo.nats.io" });
const r: Record<string, number> = {};
const sub = nc.subscribe("generate.badge");
(async () => {
for await (const m of sub) {
const badge = jc.decode(m.data) as Badge;
const name = badge.name ?? "";
if (name === "") {
return;
}
const names = name.split(" ");
const n = names[0].toLowerCase();
r[n] = (r[n] || 0) + 1;
}
})().catch();
const service = await nc.services.add({
name: "frequency_service",
version: "0.0.1",
description: "monitors names",
});
service.addEndpoint("freq", {
subject: "badge.freq",
handler: (err, msg) => {
if (err) {
// stop will stop the service, and close it with the specified error
service.stop(err).then();
return;
}
msg.respond(jc.encode(r));
},
});
const si = service.info();
service.stopped.then((err: Error | null) => {
if (err) {
console.log(`${si.name} stopped with error: ${err.message}`);
} else {
console.log(`${si.name} stopped.`);
}
});
console.log(
`${si.name} ${si.version} started with ID: ${si.id}`,
);