-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
RemoteAssetCache.js
64 lines (56 loc) · 1.62 KB
/
RemoteAssetCache.js
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
const fs = require("fs");
const fsp = fs.promises; // Node 10+
const path = require("path");
const fetch = require("node-fetch");
const shorthash = require("short-hash");
const flatCache = require("flat-cache");
const AssetCache = require("./AssetCache");
const debug = require("debug")("EleventyCacheAssets");
class RemoteAssetCache extends AssetCache {
constructor(url, cacheDirectory) {
super(shorthash(url), cacheDirectory);
this.url = url;
}
get url() {
return this._url;
}
set url(url) {
this._url = url;
}
async getResponseValue(response, type) {
if(type === "json") {
return response.json();
} else if(type === "text") {
return response.text();
}
return response.buffer();
}
async fetch(options = {}) {
if( super.isCacheValid(options.duration) ) {
return super.getCachedValue();
}
// make cacheDirectory if it does not exist.
await fsp.mkdir(this.cacheDirectory, {
recursive: true
});
try {
let response = await fetch(this.url, options.fetchOptions || {});
if(!response.ok) {
throw new Error(`Bad response for ${this.url} (${response.status}): ${response.statusText}`)
}
let body = await this.getResponseValue(response, options.type);
console.log( `Caching: ${this.url}` ); // @11ty/eleventy-cache-assets
await super.save(body, options.type);
return body;
} catch(e) {
if(this.cachedObject) {
console.log( `Error fetching ${this.url}. Message: ${e.message}`);
console.log( `Failing gracefully with an expired cache entry.` );
return super.getCachedValue();
} else {
return Promise.reject(e);
}
}
}
}
module.exports = RemoteAssetCache;