Skip to content

Commit 53cc8bf

Browse files
authored
Use deno's new native http server
2 parents 96c80de + 2954297 commit 53cc8bf

File tree

30 files changed

+754
-737
lines changed

30 files changed

+754
-737
lines changed

.github/workflows/test.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ on:
44
branches: [master]
55
jobs:
66
build:
7-
runs-on: ubuntu-16.04
7+
runs-on: ubuntu-latest
88
steps:
99
- uses: actions/checkout@master
1010
- uses: denolib/setup-deno@master

README.md

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,9 @@ JSON-RPC 2.0 library (server and client) with HTTP and WebSockets support for
1010
Takes `Methods`, `ServerRequest` and `Options`.
1111

1212
```typescript
13-
import { serve } from "https://deno.land/std@0.105.0/http/server.ts";
13+
import { listenAndServe } from "https://deno.land/std@0.107.0/http/server.ts";
1414
import { respond } from "https://deno.land/x/gentle_rpc/mod.ts";
1515

16-
const server = serve("0.0.0.0:8000");
1716
const rpcMethods = {
1817
sayHello: ([w]: [string]) => `Hello ${w}`,
1918
callNamedParameters: ({ a, b, c }: { a: number; b: number; c: string }) =>
@@ -22,14 +21,15 @@ const rpcMethods = {
2221
noise.map((el) => el.toUpperCase()).join(" "),
2322
};
2423

25-
console.log("listening on 0.0.0.0:8000");
24+
// HTTP:
25+
listenAndServe("0.0.0.0:8000", (req) => respond(rpcMethods, req));
26+
// WebSockets:
27+
listenAndServe(
28+
"0.0.0.0:8000",
29+
(req) => respond(rpcMethods, req, { proto: "ws" }),
30+
);
2631

27-
for await (const req of server) {
28-
// HTTP:
29-
respond(rpcMethods, req);
30-
// WebSockets:
31-
respond(rpcMethods, req, { proto: "ws" });
32-
}
32+
console.log("listening on 0.0.0.0:8000");
3333
```
3434

3535
#### CustomError
@@ -65,7 +65,7 @@ Takes a `Resource` for HTTP or a `WebSocket` for WebSockets and returns
6565
```typescript
6666
import { createRemote } from "https://deno.land/x/gentle_rpc/mod.ts";
6767
// Or import directly into the browser with:
68-
import { createRemote } from "https://cdn.jsdelivr.net/gh/timonson/gentle_rpc@v3.0/client/dist/remote.js";
68+
import { createRemote } from "https://cdn.jsdelivr.net/gh/timonson/gentle_rpc@v3.1/client/dist/remote.js";
6969

7070
// HTTP:
7171
const remote = createRemote("http://0.0.0.0:8000");
@@ -169,16 +169,18 @@ remote.socket.close();
169169
##### notification
170170

171171
```typescript
172-
const notification = await remote.call("animalsMakeNoise", ["wuufff"], true);
172+
const notification = await remote.call("animalsMakeNoise", ["wuufff"], {
173+
isNotification: true,
174+
});
173175
// undefined
174176
```
175177

176178
##### messaging between multiple clients
177179

178180
By using the `subscribe` method you can send messages between multiple clients.
179181
It returns an object with a generator property
180-
`{ generator: AsyncGenerator<JsonValue>}` and the methods `emit`, `emitBatch`
181-
and `unsubscribe`.
182+
`{ generator: AsyncGenerator<JsonValue>}` and the methods `emit` and
183+
`unsubscribe`.
182184

183185
Other clients can _listen to_ and _emit_ messages by _subscribing_ to the same
184186
method.
@@ -197,19 +199,17 @@ async function run(iter: AsyncGenerator<unknown>) {
197199
}
198200
}
199201

200-
const greeting = firstClient.subscribe("sayHello");
201-
const second = secondClient.subscribe("sayHello");
202+
const greetingFirst = firstClient.subscribe("sayHello");
203+
const greetingSecond = secondClient.subscribe("sayHello");
202204

203-
run(greeting.generator);
204-
run(second.generator);
205-
greeting.emit({ w: "first" });
206-
second.emitBatch([{ w: "second" }, { w: "third" }]);
205+
run(greetingFirst.generator);
206+
run(greetingSecond.generator);
207+
greetingFirst.emit(["first"]);
208+
greetingSecond.emit(["second"]);
207209
// Hello first
208210
// Hello first
209211
// Hello second
210212
// Hello second
211-
// Hello third
212-
// Hello third
213213
```
214214

215215
## Proxy API

client/dist/http.js

Lines changed: 53 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,10 @@ function _createSuper(Derived) {
122122
function _possibleConstructorReturn(self, call) {
123123
if (call && (_typeof(call) === "object" || typeof call === "function")) {
124124
return call;
125+
} else if (call !== void 0) {
126+
throw new TypeError(
127+
"Derived constructors may only return object or undefined",
128+
);
125129
}
126130
return _assertThisInitialized(self);
127131
}
@@ -345,7 +349,7 @@ var BadServerDataError = /*#__PURE__*/ function (_Error) {
345349

346350
var _super = _createSuper(BadServerDataError);
347351

348-
function BadServerDataError(id, message, errorCode, data) {
352+
function BadServerDataError(id1, message, errorCode, data1) {
349353
var _this;
350354

351355
_classCallCheck(this, BadServerDataError);
@@ -358,86 +362,87 @@ var BadServerDataError = /*#__PURE__*/ function (_Error) {
358362

359363
_defineProperty(_assertThisInitialized(_this), "data", void 0);
360364

361-
_this.id = id;
365+
_this.name = _this.constructor.name;
366+
_this.id = id1;
362367
_this.code = errorCode;
363-
_this.data = data;
368+
_this.data = data1;
364369
return _this;
365370
}
366371

367372
return BadServerDataError;
368373
}(/*#__PURE__*/ _wrapNativeSuper(Error));
369374

370-
function validateRpcBasis(data1) {
371-
return (data1 === null || data1 === void 0 ? void 0 : data1.jsonrpc) ===
372-
"2.0" &&
373-
(typeof data1.id === "number" || typeof data1.id === "string" ||
374-
data1.id === null);
375+
function validateRpcBasis(data) {
376+
return (data === null || data === void 0 ? void 0 : data.jsonrpc) === "2.0" &&
377+
(typeof data.id === "number" || typeof data.id === "string" ||
378+
data.id === null);
375379
}
376380

377-
function validateRpcSuccess(data1) {
378-
return "result" in data1;
381+
function validateRpcSuccess(data) {
382+
return "result" in data;
379383
}
380384

381-
function validateRpcFailure(data1) {
382-
var _data1$error;
385+
function validateRpcFailure(data) {
386+
var _data$error;
383387

384-
return typeof (data1 === null || data1 === void 0
388+
return typeof (data === null || data === void 0
385389
? void 0
386-
: (_data1$error = data1.error) === null || _data1$error === void 0
390+
: (_data$error = data.error) === null || _data$error === void 0
387391
? void 0
388-
: _data1$error.code) === "number" &&
389-
typeof data1.error.message === "string";
392+
: _data$error.code) === "number" &&
393+
typeof data.error.message === "string";
390394
}
391395

392-
function validateResponse(data1) {
393-
if (validateRpcBasis(data1)) {
394-
if (validateRpcSuccess(data1)) return data1;
395-
else if (validateRpcFailure(data1)) {
396+
function validateResponse(data, isNotification) {
397+
if (isNotification && data !== undefined) {
398+
throw new BadServerDataError(
399+
null,
400+
"The server's response to the notification contains unexpected data.",
401+
);
402+
}
403+
404+
if (validateRpcBasis(data)) {
405+
if (validateRpcSuccess(data)) return data;
406+
else if (validateRpcFailure(data)) {
396407
throw new BadServerDataError(
397-
data1.id,
398-
data1.error.message,
399-
data1.error.code,
400-
data1.error.data,
408+
data.id,
409+
data.error.message,
410+
data.error.code,
411+
data.error.data,
401412
);
402413
}
403414
}
404415

405416
throw new BadServerDataError(
406417
null,
407418
"The received data is no valid JSON-RPC 2.0 Response object.",
408-
null,
409419
);
410420
}
411421

412422
function send(resource, fetchInit) {
413423
return fetch(resource instanceof URL ? resource.href : resource, fetchInit)
414424
.then(function (res) {
415-
if (!res.ok) {
416-
return Promise.reject(
417-
new RangeError(
418-
"".concat(res.status, " '").concat(
419-
res.statusText,
420-
"' received instead of 200-299 range.",
421-
),
422-
),
423-
);
424-
} else if (
425-
res.status === 204 || res.headers.get("content-length") === "0"
426-
) {
427-
return undefined;
428-
} else return res.json();
425+
return res.status === 204 || res.headers.get("content-length") === "0"
426+
? undefined
427+
: res.text().then(function (text) {
428+
return text ? JSON.parse(text) : undefined;
429+
})["catch"](function (err) {
430+
return Promise.reject(
431+
new BadServerDataError(null, "The received data is invalid JSON."),
432+
);
433+
});
429434
});
430435
}
431436

432-
function processBatchArray1(rpcResponseBatch) {
437+
function processBatchArray1(rpcResponseBatch, isNotification) {
433438
return rpcResponseBatch.map(function (rpcResponse) {
434-
return validateResponse(rpcResponse).result;
439+
return validateResponse(rpcResponse, isNotification).result;
435440
});
436441
}
437442

438-
function processBatchObject1(rpcResponseBatch) {
443+
function processBatchObject1(rpcResponseBatch, isNotification) {
439444
return rpcResponseBatch.reduce(function (acc, rpcResponse) {
440-
var rpcSuccess = validateResponse(rpcResponse);
445+
var rpcSuccess = validateResponse(rpcResponse, isNotification);
441446

442447
if (rpcSuccess.id !== null) {
443448
acc[rpcSuccess.id] = rpcSuccess.result;
@@ -446,14 +451,13 @@ function processBatchObject1(rpcResponseBatch) {
446451
throw new BadServerDataError(
447452
null,
448453
"Type 'null' cannot be used as an index type.",
449-
null,
450454
);
451455
}
452456
}, {});
453457
}
454458

455459
var Remote1 = /*#__PURE__*/ function () {
456-
function Remote1(resource) {
460+
function Remote1(resource1) {
457461
var options = arguments.length > 1 && arguments[1] !== undefined
458462
? arguments[1]
459463
: {};
@@ -474,7 +478,7 @@ var Remote1 = /*#__PURE__*/ function () {
474478
method: "POST",
475479
headers: headers,
476480
});
477-
this.resource = resource;
481+
this.resource = resource1;
478482
}
479483

480484
_createClass(Remote1, [{
@@ -497,13 +501,12 @@ var Remote1 = /*#__PURE__*/ function () {
497501
Array.isArray(rpcResponseBatch) && rpcResponseBatch.length > 0
498502
) {
499503
return Array.isArray(batchObj)
500-
? processBatchArray1(rpcResponseBatch)
501-
: processBatchObject1(rpcResponseBatch);
504+
? processBatchArray1(rpcResponseBatch, isNotification)
505+
: processBatchObject1(rpcResponseBatch, isNotification);
502506
} else {
503507
throw new BadServerDataError(
504508
null,
505509
"The server returned an invalid batch response.",
506-
null,
507510
);
508511
}
509512
});
@@ -538,7 +541,7 @@ var Remote1 = /*#__PURE__*/ function () {
538541
).then(function (rpcResponse) {
539542
return rpcResponse === undefined && isNotification
540543
? undefined
541-
: validateResponse(rpcResponse).result;
544+
: validateResponse(rpcResponse, isNotification).result;
542545
});
543546
},
544547
}]);

0 commit comments

Comments
 (0)