-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstart-server.ts
111 lines (105 loc) · 3.04 KB
/
start-server.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
import { join } from 'path';
import {
loadPackageDefinition,
Server,
ServerCredentials,
ServiceClientConstructor,
} from '@grpc/grpc-js';
import { load } from '@grpc/proto-loader';
const seconds = new Date('2020-12-20').getTime();
const Genre = {
UNSPECIFIED: 0,
ACTION: 1,
DRAMA: 2,
};
const Movies = [
{
cast: ['Tom Cruise', 'Simon Pegg', 'Jeremy Renner'],
name: 'Mission: Impossible Rogue Nation',
rating: 0.97,
year: BigInt(2015),
time: {
seconds,
},
genre: Genre.ACTION,
},
{
cast: ['Tom Cruise', 'Simon Pegg', 'Henry Cavill'],
name: 'Mission: Impossible - Fallout',
rating: 0.93,
year: BigInt(2018),
time: {
seconds,
},
genre: Genre.ACTION,
},
{
cast: ['Leonardo DiCaprio', 'Jonah Hill', 'Margot Robbie'],
name: 'The Wolf of Wall Street',
rating: 0.78,
year: BigInt(2013),
time: {
seconds,
},
genre: Genre.DRAMA,
},
];
export function startServer(subscriptionInterval = 1000, debug = false): Promise<Server> {
return new Promise(async (resolve, reject) => {
try {
const logger = debug ? (...args) => console.log(...args) : () => {};
const server = new Server();
const packageDefinition = await load('./service.proto', {
includeDirs: [join(__dirname, './proto')],
});
const grpcObject = loadPackageDefinition(packageDefinition);
server.addService((grpcObject.Example as ServiceClientConstructor).service, {
getMovies(call, callback) {
console.log(JSON.stringify(call.request, null, 2))
const result = Movies.filter(movie => {
for (const [key, value] of Object.entries(call.request.movie)) {
if (movie[key] === value) {
return true;
}
}
});
const moviesResult = { result };
logger('called with MetaData:', JSON.stringify(call.metadata.getMap()));
callback(null, moviesResult);
},
async searchMoviesByCast(call) {
logger('call started');
logger('called with MetaData:', JSON.stringify(call.metadata.getMap()));
const input = call.request;
call.on('error', error => {
console.error(error);
call.end();
});
for (const movie of Movies) {
await new Promise(resolve => setTimeout(resolve, subscriptionInterval));
if (call.cancelled || call.destroyed) {
logger('call ended');
return;
}
if (movie.cast.includes(input.castName)) {
logger('call received', movie);
call.write(movie);
}
}
call.end();
},
});
server.bindAsync('0.0.0.0:50051', ServerCredentials.createInsecure(), (error, port) => {
if (error) {
reject(error);
return;
}
server.start();
logger('Server started, listening: 0.0.0.0:' + port);
resolve(server);
});
} catch (e) {
reject(e);
}
});
}