Skip to content

Commit fbe479b

Browse files
committed
chore: download of images now cached for improve performance
1 parent 1a6b1fe commit fbe479b

1 file changed

Lines changed: 11 additions & 18 deletions

File tree

src/components/utils/download.ts

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,31 +9,24 @@ export async function download(
99
url: string,
1010
format: string,
1111
): Promise<MessageMedia> {
12-
const response = await axios.get(url, {
13-
responseType: "arraybuffer",
14-
});
15-
1612
const tempDir = path.resolve(".temp");
1713
await fs.mkdir(tempDir, { recursive: true });
1814

19-
const filename = `${crypto.randomUUID()}${format}`;
15+
const hash = crypto.createHash("md5").update(url).digest("hex");
16+
const filename = `${hash}${format.startsWith(".") ? format : `.${format}`}`;
2017
const tempPath = path.join(tempDir, filename);
2118

2219
try {
23-
await fs.writeFile(tempPath, response.data, "base64");
20+
try {
21+
await fs.access(tempPath);
22+
log.info("Download", `Cache hit: ${filename}`);
23+
return MessageMedia.fromFilePath(tempPath);
24+
} catch {
25+
log.info("Download", `Cache miss: downloading ${url}`);
26+
}
2427

25-
// Schedule deletion after 1 minute
26-
setTimeout(async () => {
27-
try {
28-
await fs.unlink(tempPath);
29-
log.info("Download", `Temporary file deleted: ${tempPath}`);
30-
} catch (err) {
31-
log.error(
32-
"Download",
33-
`Failed to delete temp file: ${(err as Error).message}`,
34-
);
35-
}
36-
}, 60 * 1000);
28+
const response = await axios.get(url, { responseType: "arraybuffer" });
29+
await fs.writeFile(tempPath, response.data);
3730

3831
return MessageMedia.fromFilePath(tempPath);
3932
} catch (err) {

0 commit comments

Comments
 (0)