Skip to content

Commit 93e546b

Browse files
committed
fixed service examples and readmes
1 parent 6f4413f commit 93e546b

File tree

8 files changed

+67
-57
lines changed

8 files changed

+67
-57
lines changed

jetstream/README.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
# jetstream
1+
# JetStream
22

33
The jetstream module implements the JetStream protocol functionality for
4-
JavaScript clients.
4+
JavaScript clients. JetStream is the NATS persistence engine providing
5+
streaming, message, and worker queues with At-Least-Once semantics.
56

67
To use JetStream simply install this library, and create a `jetstream(nc)` or
78
`jetstreamManager(nc)` with a connection provided by your chosen transport

services.md renamed to services/README.md

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,23 @@
1-
# Services Framework
1+
# Services
22

3-
The Services Framework introduces a higher-level API for implementing services
4-
with NATS. NATS has always been a strong technology on which to build services,
5-
as they are easy to write, are location and DNS independent and can be scaled up
6-
or down by simply adding or removing instances of the service.
3+
The Services module introduces a higher-level API for implementing services with
4+
NATS. NATS has always been a strong technology on which to build services, as
5+
they are easy to write, are location and DNS independent and can be scaled up or
6+
down by simply adding or removing instances of the service.
77

8-
The Services Framework further streamlines their development by providing
8+
The services module further streamlines their development by providing
99
observability and standardization. The Service Framework allows your services to
1010
be discovered, queried for status and schema information without additional
1111
work.
1212

13+
To create services using the services module simply install this library and
14+
create a `new Svc(nc)`.
15+
1316
## Creating a Service
1417

1518
```typescript
16-
const service = await nc.services.add({
19+
const svc = new Svc(nc);
20+
const service = await svc.add({
1721
name: "max",
1822
version: "0.0.1",
1923
description: "returns max number in a request",
@@ -55,7 +59,7 @@ sport a different `ID`.
5559
To discover services that are running, create a monitoring client:
5660

5761
```typescript
58-
const m = nc.services.client();
62+
const m = svc.client();
5963

6064
// you can ping, request info, and stats information.
6165
// All the operations return iterators describing the services found.
@@ -76,7 +80,7 @@ await m.stats("max", id);
7680
```
7781

7882
For a more elaborate first example see:
79-
[simple example here](services/examples/01_services.ts)
83+
[simple example here](examples/01_services.ts)
8084

8185
## Multiple Endpoints
8286

@@ -132,4 +136,4 @@ For those paying attention, you can specify a callback much like in the first
132136
example, if you don't, the return value of the add endpoint is an iterator.
133137

134138
For a complete example see:
135-
[multiple endpoints](services/examples/02_multiple_endpoints.ts)
139+
[multiple endpoints](examples/02_multiple_endpoints.ts)

services/examples/01_services.ts

Lines changed: 21 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,18 @@
1313
* limitations under the License.
1414
*/
1515

16+
import { connect } from "jsr:@nats-io/[email protected]";
17+
18+
import type { QueuedIterator } from "jsr:@nats-io/[email protected]";
19+
1620
import {
17-
connect,
18-
JSONCodec,
19-
QueuedIterator,
2021
ServiceError,
2122
ServiceErrorCodeHeader,
2223
ServiceErrorHeader,
23-
ServiceMsg,
24-
ServiceStats,
25-
} from "../../src/mod.ts";
26-
import { assertEquals } from "https://deno.land/[email protected]/assert/mod.ts";
24+
Svc,
25+
} from "../src/mod.ts";
26+
import type { ServiceMsg, ServiceStats } from "../src/mod.ts";
27+
import { assertEquals } from "jsr:@std/assert";
2728

2829
// connect to NATS on demo.nats.io
2930
const nc = await connect({ servers: ["demo.nats.io"] });
@@ -40,8 +41,9 @@ const statsHandler = (): Promise<unknown> => {
4041
return Promise.resolve({ max: maxMax });
4142
};
4243

43-
// create a service - using the statsHandler and decoder
44-
const service = await nc.services.add({
44+
// create a service - using the statsHandler
45+
const svc = new Svc(nc);
46+
const service = await svc.add({
4547
name: "max",
4648
version: "0.0.1",
4749
description: "returns max number in a request",
@@ -63,7 +65,6 @@ service.stopped.then((err: Error | null) => {
6365
// starting the service as an async function so that
6466
// we can have this example be in a single file
6567
(async () => {
66-
const jc = JSONCodec<number>();
6768
for await (const r of max) {
6869
// most of the logic is about validating the input
6970
// and returning an error to the client if the input
@@ -82,7 +83,7 @@ service.stopped.then((err: Error | null) => {
8283
`${service.info().name} calculated a response of ${max} from ${a.length} values`,
8384
);
8485
// finally we respond with a JSON number payload with the maximum value
85-
r.respond(jc.encode(max));
86+
r.respond(JSON.stringify(max));
8687
})
8788
.catch((err) => {
8889
// if we are here, the initial processing of the array failed
@@ -95,18 +96,17 @@ service.stopped.then((err: Error | null) => {
9596
r.respondError(
9697
(err as ServiceError).code || 400,
9798
err.message,
98-
jc.encode(0),
99+
JSON.stringify(0),
99100
);
100101
});
101102
}
102103
})();
103104

104105
// decoder extracts a JSON payload and expects it to be an array of numbers
105106
function decoder(r: ServiceMsg): Promise<number[]> {
106-
const jc = JSONCodec<number[]>();
107107
try {
108108
// decode JSON
109-
const a = jc.decode(r.data);
109+
const a = r.json();
110110
// if not an array, this is bad input
111111
if (!Array.isArray(a)) {
112112
return Promise.reject(
@@ -145,7 +145,7 @@ await nc.request("max").then((r) => {
145145
assertEquals(r.headers?.get(ServiceErrorCodeHeader), "400");
146146
});
147147
// call it with an empty array also expecting an error response
148-
await nc.request("max", JSONCodec().encode([])).then((r) => {
148+
await nc.request("max", JSON.stringify([])).then((r) => {
149149
// Here's an alternative way of checking if the response is an error response
150150
assertEquals(ServiceError.isServiceError(r), true);
151151
const se = ServiceError.toServiceError(r);
@@ -154,12 +154,12 @@ await nc.request("max", JSONCodec().encode([])).then((r) => {
154154
});
155155

156156
// call it with valid arguments
157-
await nc.request("max", JSONCodec().encode([1, 10, 100])).then((r) => {
157+
await nc.request("max", JSON.stringify([1, 10, 100])).then((r) => {
158158
// no error headers
159159
assertEquals(ServiceError.isServiceError(r), false);
160160
// and the response is on the payload, so we process the JSON we
161161
// got from the service
162-
assertEquals(JSONCodec().decode(r.data), 100);
162+
assertEquals(r.json<number>(), 100);
163163
});
164164

165165
// Monitoring
@@ -177,7 +177,7 @@ async function collect<T>(p: Promise<QueuedIterator<T>>): Promise<T[]> {
177177
return buf;
178178
}
179179

180-
const m = nc.services.client();
180+
const m = svc.client();
181181
// discover
182182
const found = await collect(m.ping());
183183
assertEquals(found.length, 1);
@@ -199,10 +199,9 @@ await collect(m.stats("max", found[0].id));
199199
// The id is also optional, but you must know it (from ping or one of
200200
// other requests that allowed you to discover the service) to
201201
// target the service specifically as we do here:
202-
const stats = JSONCodec<ServiceStats>().decode(
203-
// note the name of the service matches in case what was specified
204-
(await nc.request(`$SRV.STATS.max.${found[0].id}`)).data,
205-
);
202+
const r = await nc.request(`$SRV.STATS.max.${found[0].id}`);
203+
const stats = r.json<ServiceStats>();
204+
206205
assertEquals(stats.name, "max");
207206
assertEquals(stats.endpoints?.[0].num_requests, 3);
208207
assertEquals((stats.endpoints?.[0].data as { max: number }).max, 100);

services/examples/02_multiple_endpoints.ts

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,16 @@
1313
* limitations under the License.
1414
*/
1515

16-
import { connect, JSONCodec, ServiceError, ServiceMsg } from "../../src/mod.ts";
17-
18-
const jc = JSONCodec();
16+
import { connect } from "jsr:@nats-io/[email protected]";
17+
import { ServiceError, Svc } from "../src/mod.ts";
18+
import type { ServiceMsg } from "../src/mod.ts";
1919

2020
// connect to NATS on demo.nats.io
2121
const nc = await connect({ servers: ["demo.nats.io"] });
2222

2323
// create a service - using the statsHandler and decoder
24-
const calc = await nc.services.add({
24+
const svc = new Svc(nc);
25+
const calc = await svc.add({
2526
name: "calc",
2627
version: "0.0.1",
2728
description: "example calculator service",
@@ -61,7 +62,7 @@ const sums = g.addEndpoint("sum", {
6162
const s = numbers.reduce((sum, v) => {
6263
return sum + v;
6364
});
64-
m.respond(jc.encode(s));
65+
m.respond(JSON.stringify(s));
6566
}
6667
})().then();
6768

@@ -76,7 +77,7 @@ g.addEndpoint("average", {
7677
const sum = numbers.reduce((sum, v) => {
7778
return sum + v;
7879
});
79-
m.respond(jc.encode(sum / numbers.length));
80+
m.respond(JSON.stringify(sum / numbers.length));
8081
},
8182
metadata: {
8283
"input": "JSON number array",
@@ -95,7 +96,7 @@ g.addEndpoint("min", {
9596
const min = numbers.reduce((n, v) => {
9697
return Math.min(n, v);
9798
});
98-
m.respond(jc.encode(min));
99+
m.respond(JSON.stringify(min));
99100
},
100101
metadata: {
101102
"input": "JSON number array",
@@ -113,7 +114,7 @@ g.addEndpoint("max", {
113114
const max = numbers.reduce((n, v) => {
114115
return Math.max(n, v);
115116
});
116-
m.respond(jc.encode(max));
117+
m.respond(JSON.stringify(max));
117118
},
118119
metadata: {
119120
"input": "JSON number array",
@@ -127,7 +128,7 @@ calc.stopped.then((err: Error | null) => {
127128

128129
// Now we switch gears and look at a client making a request
129130
async function calculate(op: string, a: number[]): Promise<void> {
130-
const r = await nc.request(`calc.${op}`, jc.encode(a));
131+
const r = await nc.request(`calc.${op}`, JSON.stringify(a));
131132
if (ServiceError.isServiceError(r)) {
132133
console.log(ServiceError.toServiceError(r));
133134
return;

services/examples/03_bigdata-client.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,13 @@
1212
* See the License for the specific language governing permissions and
1313
* limitations under the License.
1414
*/
15-
import { parse } from "https://deno.land/[email protected]/flags/mod.ts";
16-
import { connect, ConnectionOptions, RequestStrategy } from "../../src/mod.ts";
15+
import { parse } from "jsr:@std/flags";
16+
import {
17+
connect,
18+
RequestStrategy,
19+
} from "jsr:@nats-io/[email protected]";
20+
import type { ConnectionOptions } from "jsr:@nats-io/[email protected]";
21+
1722
import { humanizeBytes } from "./03_util.ts";
1823

1924
const argv = parse(
@@ -25,7 +30,7 @@ const argv = parse(
2530
"c": ["chunk"],
2631
},
2732
default: {
28-
s: "127.0.0.1:4222",
33+
s: "demo.nats.io",
2934
c: 0,
3035
a: 1024 * 1024,
3136
},

services/examples/03_bigdata.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,14 @@
1313
* limitations under the License.
1414
*/
1515

16-
import { connect } from "../../src/mod.ts";
17-
import { DataRequest, humanizeBytes } from "./03_util.ts";
16+
import { connect } from "jsr:@nats-io/[email protected]";
17+
import { Svc } from "../src/mod.ts";
18+
import { humanizeBytes } from "./03_util.ts";
19+
import type { DataRequest } from "./03_util.ts";
1820

19-
const nc = await connect();
20-
const srv = await nc.services.add({
21+
const nc = await connect({ servers: "demo.nats.io" });
22+
const svc = new Svc(nc);
23+
const srv = await svc.add({
2124
name: "big-data",
2225
version: "0.0.1",
2326
});

services/src/types.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import {
1+
import type {
22
Msg,
33
Nanos,
44
NatsError,

services/tests/service-check.ts

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,9 @@
1515

1616
import { cli } from "https://deno.land/x/[email protected]/mod.ts";
1717
import { connect } from "jsr:@nats-io/[email protected]";
18-
import {
19-
collect,
20-
NatsConnection,
21-
parseSemVer,
22-
StringCodec,
23-
} from "@nats-io/nats-core/internal";
18+
import { collect, parseSemVer, StringCodec } from "@nats-io/nats-core/internal";
19+
20+
import type { NatsConnection } from "@nats-io/nats-core/internal";
2421

2522
import type { ServiceIdentity, ServiceInfo, ServiceStats } from "../src/mod.ts";
2623
import {

0 commit comments

Comments
 (0)