-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.ts
98 lines (77 loc) · 2.38 KB
/
client.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
import { createConnection } from 'net';
import type { Socket } from 'net';
import * as encoder from './encoder';
import * as decoder from './decoder';
export default class SpideyDbClient {
private host = 'localhost';
private port = 6425;
private socket?: Socket;
private handleServerConnection(): void {
console.log('connected to spidey db');
}
private handleServerDisconnect(): void {
console.log('disconnected from spidey db');
}
async send(request: string[]): Promise<string | string[]> {
return new Promise((resolve, reject) => {
if (!this.socket) {
return reject('not connected');
}
this.socket.once('data', (data: Buffer) => {
const response = decoder.decode(data);
if (Array.isArray(response)) {
resolve(response as string[]);
} else {
resolve(String(response));
}
});
const respRequest = encoder.encodeArray(
request.map(encoder.encodeBulkString)
);
this.socket.write(respRequest);
});
}
async isConnected(): Promise<boolean> {
const response = await this.send(['PING']);
return response === 'PONG';
}
async setVertex(key: string, value: string): Promise<boolean> {
const response = await this.send(['SETVERTEX', key, value]);
return String(response) === 'OK';
}
async getVertex(key: string): Promise<string> {
const response = await this.send(['GETVERTEX', key]);
return String(response);
}
async setEdge(srcVertexKey: string, destVertexKey: string): Promise<boolean> {
const response = await this.send(['SETEDGE', srcVertexKey, destVertexKey]);
return String(response) === 'OK';
}
async getNeighbors(vertexKey: string, distance: number): Promise<string[]> {
const response = await this.send([
'GETNEIGHBORS',
vertexKey,
String(distance),
]);
if (!Array.isArray(response)) {
throw Error('unexpected response');
}
return response;
}
async getGraph(): Promise<string[]> {
const response = await this.send(['GETGRAPH']);
if (!Array.isArray(response)) {
throw Error('unexpected response');
}
return response;
}
connect(): void {
const client = createConnection(
this.port,
this.host,
this.handleServerConnection.bind(this)
);
client.on('end', this.handleServerDisconnect.bind(this));
this.socket = client;
}
}