1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | const fs = require("fs-extra");
|
4 | async function updateCache(cachePath, cache) {
|
5 | await fs.ensureFile(cachePath);
|
6 | await fs.writeJSON(cachePath, cache);
|
7 | }
|
8 | exports.updateCache = updateCache;
|
9 | function _mtime(f) {
|
10 | return fs.statSync(f).mtime;
|
11 | }
|
12 | function _isStale(cachePath, cacheDuration) {
|
13 | const past = new Date();
|
14 | past.setSeconds(past.getSeconds() - cacheDuration);
|
15 | return past.getTime() > _mtime(cachePath).getTime();
|
16 | }
|
17 | async function fetchCache(cachePath, cacheDuration, options) {
|
18 | const cachePresent = fs.existsSync(cachePath);
|
19 | if (cachePresent && !_isStale(cachePath, cacheDuration)) {
|
20 | return fs.readJSON(cachePath);
|
21 | }
|
22 | const cache = await options.cacheFn();
|
23 |
|
24 | await updateCache(cachePath, cache);
|
25 | return cache;
|
26 | }
|
27 | exports.fetchCache = fetchCache;
|