-
Notifications
You must be signed in to change notification settings - Fork 0
/
node-helper.ts
96 lines (88 loc) · 1.89 KB
/
node-helper.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
import { exec } from "child_process";
import util from "util";
import process from "process";
import readline from "readline";
import nodeFetch, { Response } from "node-fetch";
/**
* A collection of node helper functions
*/
/**
* Execute a command
*
* @param command
*/
async function execute(command: string): Promise<string> {
return new Promise((resolve, reject) => {
exec(command, (err, stdout, stderr) => {
if (err) {
reject(stderr);
}
resolve(stdout);
});
});
}
/**
* Read input from the user
*
* @param input
* @returns {Promise<string>}
*/
async function input(input: string): Promise<string> {
return new Promise((resolve) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question(`${input} `, (answer: string) => {
rl.close();
resolve(answer);
});
});
}
/**
* Whether the user accepted the input
*
* @param input
*/
function isAnswerYes(input: string): boolean | null {
return !!input.match(/[yY]/g);
}
/**
* Fetch a file from an endpoint
*
* @param endpoint
* @param bearerToken
*/
async function fetchFile(
endpoint: string,
bearerToken?: string
): Promise<ArrayBuffer> {
const options = bearerToken
? {
headers: { Authorization: `Bearer ${bearerToken}` },
}
: {};
const response = await nodeFetch(endpoint, options);
const data = await response.arrayBuffer();
return data;
}
/**
* Fetch anything.
* Uses node-fetch under the hood.
*
* @param endpoint
* @param bearerToken
*/
async function fetch(
endpoint: string,
bearerToken?: string
): Promise<Response> {
const options = bearerToken
? {
headers: { Authorization: `Bearer ${bearerToken}` },
}
: {};
const response = await nodeFetch(endpoint, options);
return response;
}
export default { execute, isAnswerYes, input, fetchFile, fetch };