1 | const got = require("got");
|
2 |
|
3 | class NgrokClientError extends Error {
|
4 | constructor(message, response, body) {
|
5 | super(message);
|
6 | this.name = "NgrokClientError";
|
7 | this.response = response;
|
8 | this.body = body;
|
9 | }
|
10 | }
|
11 |
|
12 | class NgrokClient {
|
13 | constructor(processUrl) {
|
14 | this.internalApi = got.extend({
|
15 | prefixUrl: processUrl,
|
16 | retry: 0,
|
17 | });
|
18 | }
|
19 |
|
20 | async request(method, path, options = {}) {
|
21 | try {
|
22 | if (method === "get") {
|
23 | return await this.internalApi
|
24 | .get(path, { searchParams: options })
|
25 | .json();
|
26 | } else {
|
27 | return await this.internalApi[method](path, { json: options }).json();
|
28 | }
|
29 | } catch (error) {
|
30 | let clientError;
|
31 | try {
|
32 | const response = JSON.parse(error.response.body);
|
33 | clientError = new NgrokClientError(
|
34 | response.msg,
|
35 | error.response,
|
36 | response
|
37 | );
|
38 | } catch (e) {
|
39 | clientError = new NgrokClientError(
|
40 | error.response.body,
|
41 | error.response,
|
42 | error.response.body
|
43 | );
|
44 | }
|
45 | throw clientError;
|
46 | }
|
47 | }
|
48 |
|
49 | async booleanRequest(method, path, options = {}) {
|
50 | try {
|
51 | return await this.internalApi[method](path, { json: options }).then(
|
52 | (response) => response.statusCode === 204
|
53 | );
|
54 | } catch (error) {
|
55 | const response = JSON.parse(error.response.body);
|
56 | throw new NgrokClientError(response.msg, error.response, response);
|
57 | }
|
58 | }
|
59 |
|
60 | listTunnels() {
|
61 | return this.request("get", "api/tunnels");
|
62 | }
|
63 |
|
64 | startTunnel(options = {}) {
|
65 | return this.request("post", "api/tunnels", options);
|
66 | }
|
67 |
|
68 | tunnelDetail(name) {
|
69 | return this.request("get", `api/tunnels/${name}`);
|
70 | }
|
71 |
|
72 | stopTunnel(name) {
|
73 | if (typeof name === "undefined" || name.length === 0) {
|
74 | throw new Error("To stop a tunnel, please provide a name.");
|
75 | }
|
76 | return this.booleanRequest("delete", `api/tunnels/${name}`);
|
77 | }
|
78 |
|
79 | listRequests(options) {
|
80 | return this.request("get", "api/requests/http", options);
|
81 | }
|
82 |
|
83 | replayRequest(id, tunnelName) {
|
84 | return this.booleanRequest("post", "api/requests/http", { id, tunnelName });
|
85 | }
|
86 |
|
87 | deleteAllRequests() {
|
88 | return this.booleanRequest("delete", "api/requests/http");
|
89 | }
|
90 |
|
91 | requestDetail(id) {
|
92 | if (typeof id === "undefined" || id.length === 0) {
|
93 | throw new Error("To get the details of a request, please provide an id.");
|
94 | }
|
95 | return this.request("get", `api/requests/http/${id}`);
|
96 | }
|
97 | }
|
98 |
|
99 | module.exports = { NgrokClient, NgrokClientError };
|