This repository was archived by the owner on Feb 14, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfetchJSON.js
More file actions
80 lines (66 loc) · 2.09 KB
/
fetchJSON.js
File metadata and controls
80 lines (66 loc) · 2.09 KB
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
import fsp from "fs/promises";
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const projectDir = path.resolve(__dirname, "./");
const distDir = path.resolve(projectDir, "public");
export async function fetchJSON(outputDir, apiUrl, options = {})
{
if (!outputDir || typeof outputDir !== "string")
{
throw new Error("outputDir must be a non-empty string");
}
if (!apiUrl || typeof apiUrl !== "string")
{
throw new Error("apiUrl must be a non-empty string");
}
const filename = options.filename || "someJSONFile.json";
const timeoutMs = Number.isFinite(options.timeoutMs)
? options.timeoutMs
: 15000;
const controller = new AbortController();
const t = setTimeout(() => controller.abort(), timeoutMs);
let json;
try
{
const res = await fetch(apiUrl, {
signal: controller.signal,
headers: {
"User-Agent": "RedotEngine/1.0 (+https://redotengine.org)",
"Accept": "application/vnd.github+json",
},
});
if (!res.ok)
{
throw new Error(
`Failed to fetch GitHub release: ${ res.status } ${ res.statusText }`
);
}
json = await res.json();
} finally
{
clearTimeout(t);
}
await fsp.mkdir(outputDir, { recursive: true });
const payload = {
source: apiUrl,
generatedAt: new Date().toISOString(),
data: json,
};
const filePath = path.join(outputDir, filename);
await fsp.writeFile(filePath, JSON.stringify(payload, null, 2), "utf8");
return { filePath, apiUrl };
}
const apiUrl =
"https://api.github.com/repos/Redot-Engine/redot-engine/releases/latest";
fetchJSON(path.join(distDir, "data"), apiUrl, {
filename: "latest-release.json",
})
.then(({ filePath }) => console.log("Saved:", filePath))
.catch((err) =>
{
console.error(err);
process.exitCode = 1;
});