Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ulixee
GitHub Repository: ulixee/secret-agent
Path: blob/main/client/connections/ConnectionFactory.ts
2605 views
1
import Log from '@secret-agent/commons/Logger';
2
import IConnectionToCoreOptions from '../interfaces/IConnectionToCoreOptions';
3
import ConnectionToCore from './ConnectionToCore';
4
import RemoteConnectionToCore from './RemoteConnectionToCore';
5
6
const { log } = Log(module);
7
8
export default class ConnectionFactory {
9
public static createLocalConnection?: (options: IConnectionToCoreOptions) => ConnectionToCore;
10
11
public static createConnection(
12
options: IConnectionToCoreOptions | ConnectionToCore,
13
): ConnectionToCore {
14
if (options instanceof ConnectionToCore) {
15
// NOTE: don't run connect on an instance
16
return options;
17
}
18
19
let connection: ConnectionToCore;
20
if (options.host) {
21
connection = new RemoteConnectionToCore(options);
22
} else {
23
if (!this.createLocalConnection) {
24
throw new Error(
25
`You need to install the full "npm i secret-agent" installation to use local connections.
26
27
If you meant to connect to a remote host, include the "host" parameter for your connection`,
28
);
29
}
30
connection = this.createLocalConnection(options);
31
}
32
33
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
34
const onError = (error: Error) => {
35
if (error) {
36
log.error('Error connecting to core', {
37
error,
38
sessionId: null,
39
});
40
}
41
};
42
43
connection.connect(true).then(onError).catch(onError);
44
45
return connection;
46
}
47
}
48
49