forked from bubenshchykov/ngrok
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
72 lines (63 loc) · 1.72 KB
/
index.js
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
const { NgrokClient } = require('./src/client');
const uuid = require('uuid');
const {getProcess, killProcess, setAuthtoken, getVersion} = require('./src/process');
const { defaults, validate, isRetriable } = require("./src/utils");
let processUrl = null;
let ngrokClient = null;
async function connect (opts) {
opts = defaults(opts);
validate(opts);
if (opts.authtoken) {
await setAuthtoken(opts);
}
processUrl = await getProcess(opts);
ngrokClient = new NgrokClient(processUrl);
return connectRetry(opts);
}
async function connectRetry (opts, retryCount = 0) {
opts.name = String(opts.name || uuid.v4());
try {
const response = await ngrokClient.startTunnel(opts);
return response.public_url;
} catch (err) {
if (!isRetriable(err) || retryCount >= 100) {
throw(err);
}
await new Promise((resolve) => setTimeout(resolve, 200));
return connectRetry(opts, ++retryCount);
}
}
async function disconnect (publicUrl) {
if (!ngrokClient) return;
const tunnels = (await ngrokClient.listTunnels()).tunnels;
if (!publicUrl) {
const disconnectAll = tunnels.map(tunnel => disconnect(tunnel.public_url) );
return Promise.all(disconnectAll);
}
const tunnelDetails = tunnels.find(tunnel => tunnel.public_url === publicUrl);
if (!tunnelDetails) {
throw new Error(`there is no tunnel with url: ${publicUrl}`)
}
return ngrokClient.stopTunnel(tunnelDetails.name);
}
async function kill () {
if (!ngrokClient) return;
await killProcess();
ngrokClient = null;
tunnels = {}
}
function getUrl() {
return processUrl;
}
function getApi() {
return ngrokClient;
}
module.exports = {
connect,
disconnect,
authtoken: setAuthtoken,
kill,
getUrl,
getApi,
getVersion
};