-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
StandaloneConnector.ts
83 lines (73 loc) · 2.24 KB
/
StandaloneConnector.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
import { createConnection, TcpNetConnectOpts, IpcNetConnectOpts } from "net";
import { connect as createTLSConnection, SecureContextOptions } from "tls";
import { CONNECTION_CLOSED_ERROR_MSG } from "../utils";
import AbstractConnector, { ErrorEmitter } from "./AbstractConnector";
import { NetStream } from "../types";
export function isIIpcConnectionOptions(
value: any
): value is IIpcConnectionOptions {
return value.path;
}
export interface ITcpConnectionOptions extends TcpNetConnectOpts {
tls?: SecureContextOptions;
}
export interface IIpcConnectionOptions extends IpcNetConnectOpts {
tls?: SecureContextOptions;
}
export default class StandaloneConnector extends AbstractConnector {
constructor(
protected options: ITcpConnectionOptions | IIpcConnectionOptions
) {
super();
}
public connect(_: ErrorEmitter) {
const { options } = this;
this.connecting = true;
let connectionOptions: any;
if (isIIpcConnectionOptions(options)) {
connectionOptions = {
path: options.path
};
} else {
connectionOptions = {};
if (options.port != null) {
connectionOptions.port = options.port;
}
if (options.host != null) {
connectionOptions.host = options.host;
}
if (options.family != null) {
connectionOptions.family = options.family;
}
}
if (options.tls) {
Object.assign(connectionOptions, options.tls);
}
// TODO:
// We use native Promise here since other Promise
// implementation may use different schedulers that
// cause issue when the stream is resolved in the
// next tick.
// Should use the provided promise in the next major
// version and do not connect before resolved.
return new Promise<NetStream>((resolve, reject) => {
process.nextTick(() => {
if (!this.connecting) {
reject(new Error(CONNECTION_CLOSED_ERROR_MSG));
return;
}
try {
if (options.tls) {
this.stream = createTLSConnection(connectionOptions);
} else {
this.stream = createConnection(connectionOptions);
}
} catch (err) {
reject(err);
return;
}
resolve(this.stream);
});
});
}
}