This repository has been archived by the owner on Feb 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.ts
112 lines (101 loc) · 3.31 KB
/
index.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/**
* @license
* Copyright (c) Aiden.ai
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import * as express from 'express';
import { numberServiceDefinition, NumberService } from './service';
import * as http from 'http';
import { NodeHttpTransport } from '@improbable-eng/grpc-web-node-http-transport';
import { getNumberHandler } from './handler';
import { ModuleRpcClient } from '../../client';
import { ModuleRpcCommon } from '../../common';
import { AssertionError } from 'assert';
import { ModuleRpcContextServer } from '../../context/server';
import { ModuleRpcProtocolServer } from '../../protocol/server';
import { ModuleRpcProtocolClient } from '../../protocol/client';
main().catch(
/* istanbul ignore next */
err => {
console.error(err);
process.exit(1);
},
);
async function main() {
// We launch an Express server, register the RPC routes using the
// `grpc_web` protocol, initialize a `grpc_web` client connected to this server
// and perform some remote procedure calls.
const server = setupServer();
try {
await clientInteraction(`http://127.0.0.1:${server.address().port}/api`);
} finally {
server.close();
}
}
function setupServer() {
const app = express();
app.use(
'/api',
ModuleRpcProtocolServer.registerRpcRoutes(
numberServiceDefinition,
getNumberHandler(),
{
serverContextConnector: new ModuleRpcContextServer.EmptyServerContextConnector(),
},
),
);
const server = http.createServer(app).listen();
const port = server.address().port;
app.set('port', port);
return server;
}
async function clientInteraction(remoteAddress: string) {
const client = ModuleRpcProtocolClient.getRpcClient(numberServiceDefinition, {
remoteAddress,
getGrpcWebTransport: NodeHttpTransport(),
});
// We call our unary method
const { value } = await client.increment({ value: 10 });
console.log('Value is', value);
// Now we convert a server stream into a promise. The promise resolves to
// an array containing all the messages that were streamed before the 'complete'
// event was emitted.
const result = await ModuleRpcClient.streamAsPromise(streamNumbers(client));
console.log('ping: all messages:', result);
// Here, we cancel the call right in the middle of streaming. An exception is thrown.
try {
const stream = streamNumbers(client).on('ready', () => {
setTimeout(() => stream.cancel(), 2000);
});
await ModuleRpcClient.streamAsPromise(stream);
throw new AssertionError({ message: 'expected cancelation error' });
} catch (err) {
console.error('Expected cancelation error:', err);
}
}
function streamNumbers(
client: ModuleRpcClient.ServiceMethodMap<NumberService>,
): ModuleRpcClient.Stream<
ModuleRpcCommon.ResponseFor<NumberService, 'streamNumbers'>
> {
return client
.streamNumbers({ max: 3, sleepMs: 500 })
.on('ready', () => {
console.log('ping: onReady()');
})
.on('message', message => {
console.log(`ping: onMessage(${JSON.stringify(message)})`);
})
.on('canceled', () => {
console.log('ping: canceled');
})
.on(
'error',
/* istanbul ignore next */
err => {
console.log('ping: error (not supposed to happen):', err);
},
);
}