-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
38 lines (26 loc) · 828 Bytes
/
utils.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
import * as fs from "fs"
import * as path from "path"
import fetch from "node-fetch"
const { readFile, writeFile, stat } = fs.promises
const CACHE_DIR = "./external-data"
const fileExists = async path => !!(await stat(path).catch(e => false))
async function generateDataWithCache(dir, fileName, generateFunction) {
const filePath = path.join(dir, fileName)
const exists = await fileExists(filePath)
if (!exists) {
const data = await generateFunction()
await writeFile(filePath, data)
}
const buffer = await readFile(filePath)
return buffer.toString()
}
async function fetchWithCache(url, cacheFile) {
return await generateDataWithCache(CACHE_DIR, cacheFile, async ()=> {
const resp = await fetch(url)
return await resp.text()
})
}
export {
fetchWithCache,
generateDataWithCache
}