This repository was archived by the owner on Aug 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.ts
More file actions
48 lines (44 loc) · 1.35 KB
/
cache.ts
File metadata and controls
48 lines (44 loc) · 1.35 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
import {
existsSync,
mkdirSync,
readFileSync,
statSync,
writeFileSync,
} from "fs";
import yargs from "yargs";
import { hideBin } from "yargs/helpers";
const args = yargs(hideBin(process.argv)).argv;
export const getCacheDir = () => (args as never)["cache-dir"] || "cache";
export const syncScrapeCache = async <T>(
scrapeDirName: string,
fileName: string,
url: string,
fetchFn: (url: string) => Promise<T>,
postGetFromCacheTransformFn: (buffer: Buffer) => T,
preSetInCacheTransformFn: (output: T) => string | Promise<string>
) => {
const cacheDirName = `${getCacheDir()}/${scrapeDirName}`;
const cacheFileName = `${cacheDirName}/${fileName}`;
let scrapeOutput;
if (existsSync(cacheFileName)) {
console.debug(" Data exists in cache");
scrapeOutput = postGetFromCacheTransformFn(readFileSync(cacheFileName));
} else {
if (!existsSync(cacheDirName)) {
mkdirSync(cacheDirName, { recursive: true });
}
try {
scrapeOutput = await fetchFn(url);
writeFileSync(
cacheFileName,
await preSetInCacheTransformFn(scrapeOutput)
);
} catch (e) {
console.error(`Scraping of ${url} failed: ${e}`);
return;
}
}
return scrapeOutput;
};
export const getScrapeCacheTime = (scrapeDirName: string, fileName: string) =>
statSync(`${getCacheDir()}/${scrapeDirName}/${fileName}`).mtime;