This repository has been archived by the owner on Feb 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpRequest.mjs
62 lines (55 loc) · 2.18 KB
/
httpRequest.mjs
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
import { tmpdir } from "node:os";
import fs from "node:fs";
import path from "node:path";
import got from "got";
export async function saveFile(url, options) {
let fileSave = path.join(tmpdir(), "bdscore_"+(Math.random()*155515151).toFixed()+"_raw_bdscore_"+path.basename(url));
const Headers = {};
if (options) {
if (options.filePath && typeof options.filePath === "string") fileSave = options.filePath;
if (options.headers) Object.keys(options.headers).forEach(key => Headers[key] = String(options.headers[key]));
}
const gotStream = got.stream({url, headers: Headers, isStream: true});
gotStream.pipe(fs.createWriteStream(fileSave, {autoClose: false}));
await new Promise((done, reject) => {
gotStream.on("end", () => setTimeout(done, 1000));
gotStream.on("error", reject);
});
return fileSave;
}
export async function getBuffer(url, options) {
const Headers = {};
let Body;
if (options) {
if (options.headers) Object.keys(options.headers).forEach(key => Headers[key] = options.headers[key]);
if (options.body) Body = options.body;
}
const data = await got(url, {
headers: Headers,
body: Body,
method: (options?.method||"GET").toUpperCase(),
responseType: "buffer"
});
return Buffer.from(data.body);
}
export async function getJSON(url, options) {
return getBuffer(url, {
body: options?.body,
headers: options?.headers,
method: options?.method
}).then(res => JSON.parse(res.toString("utf8")));
}
export async function GithubRelease(username, repo) {
let fullRepo = username;
if (!username) throw new Error("Repository is required, example: GithubRelease(\"Username/repo\") or GithubRelease(\"Username\", \"repo\")");
if (repo) {
if (!/\//.test(fullRepo)) fullRepo += "/"+repo;
}
return getJSON(`https://api.github.com/repos/${fullRepo}/releases?per_page=100`);
}
export async function githubTree(username, repo, tree) {
const validate = /^[a-zA-Z0-9_\-]+$/;
if (!validate.test(username)) throw new Error("Invalid username");
if (!validate.test(repo)) throw new Error("Invalid repository name");
return getJSON<githubTree>(`https://api.github.com/repos/${username}/${repo}/git/trees/${tree}?recursive=true`);
}