-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathservice.ts
63 lines (57 loc) · 1.62 KB
/
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
58
59
60
61
62
63
import { connect, JSONCodec, ServiceError } from "./natslib.ts";
import { generateBadge } from "./generator.ts";
type Badge = {
name: string;
company?: string;
};
const jc = JSONCodec<Badge>();
const nc = await connect({ servers: "demo.nats.io" });
const service = await nc.services.add({
name: "badge_generator",
version: "0.0.1",
description: "Generates a RethinkConn badge",
});
service.addEndpoint("generate", {
subject: "generate.badge",
metadata: {
"request": "{ name: string, company?: string }",
"response": "Uint8Array",
},
handler: (err, msg) => {
if (err) {
// stop will stop the service, and close it with the specified error
service.stop(err).then();
return;
}
const req = jc.decode(msg.data);
if (typeof req.name !== "string" || req.name.length === 0) {
console.log(
`${service.info().name} is rejecting a request without a name`,
);
// you can report an error to the client
msg.respondError(400, "name is required");
return;
}
return generateBadge(req)
.then((d) => {
msg.respond(d);
})
.catch((err) => {
const sr = ServiceError.toServiceError(err);
msg.respondError(sr?.code, sr?.message);
});
},
});
const si = service.info();
// you can monitor if your service closes by awaiting done - it resolves
// to null or an error
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}`,
);