Skip to content

Commit

Permalink
Minor refactor, fixes #31
Browse files Browse the repository at this point in the history
  • Loading branch information
zachleat committed Mar 4, 2024
1 parent a109b19 commit 2361777
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 20 deletions.
14 changes: 6 additions & 8 deletions sample.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,12 @@ const AssetCache = saveLocal.AssetCache;
// });
// promises.push(json);

// let asset = new AssetCache("twitter-followers-eleven_ty");
// if(asset.isCacheValid("4d")) {
// console.log( "Found cached value" );
// console.log( await asset.getCachedValue() );
// } else {
// console.log( "Saving value" );
// asset.save({ followers: 42 }, "json");
// }
let asset = new AssetCache("twitter-followers-eleven_ty");
if(asset.isCacheValid("4d")) {
console.log( await asset.getCachedValue() );
} else {
asset.save({ followers: 42 }, "json");
}

await Promise.all(promises);

Expand Down
21 changes: 19 additions & 2 deletions src/AssetCache.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,21 @@ const debug = require("debug")("EleventyCacheAssets");

class AssetCache {
constructor(uniqueKey, cacheDirectory, options = {}) {
this.uniqueKey = uniqueKey;
this.hash = AssetCache.getHash(uniqueKey, options.hashLength);
this.cacheDirectory = cacheDirectory || ".cache";
this.defaultDuration = "1d";
this.options = options;
}

log(message) {
if(this.options.verbose) {
console.log(`[11ty/eleventy-fetch] ${message}`);
} else {
debug(message);
}
}

// Defult hashLength also set in global options, duplicated here for tests
static getHash(url, hashLength = 30) {
let hash = createHash("sha256");
Expand Down Expand Up @@ -60,7 +69,7 @@ class AssetCache {
get rootDir() {
// Work in an AWS Lambda (serverless)
// https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html

// Bad: LAMBDA_TASK_ROOT is /var/task/ on AWS so we must use ELEVENTY_ROOT
// When using ELEVENTY_ROOT, cacheDirectory must be relative
// (we are bundling the cache files into the serverless function)
Expand Down Expand Up @@ -132,8 +141,12 @@ class AssetCache {
if(type === "json") {
contents = JSON.stringify(contents);
}

let contentPath = this.getCachedContentsPath(type);

// the contents must exist before the cache metadata are saved below
await fsp.writeFile(this.getCachedContentsPath(type), contents);
await fsp.writeFile(contentPath, contents);
debug(`Writing ${contentPath}`);

let cache = this.cache;
cache.setKey(this.hash, {
Expand All @@ -145,6 +158,8 @@ class AssetCache {

async getCachedContents(type) {
let contentPath = this.getCachedContentsPath(type);
debug(`Fetching from cache ${contentPath}`);

if(type === "json") {
return require(contentPath);
}
Expand Down Expand Up @@ -211,9 +226,11 @@ class AssetCache {
async fetch(options) {
if( this.isCacheValid(options.duration) ) {
// promise
this.log( `Using cached version of: ${this.uniqueKey}` );
return this.getCachedValue();
}

this.log( `Saving ${this.uniqueKey} to ${this.cacheFilename}` );
await this.save(this.source, options.type);

return this.source;
Expand Down
12 changes: 2 additions & 10 deletions src/RemoteAssetCache.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,6 @@ class RemoteAssetCache extends AssetCache {
return url;
}

log(message) {
if(this.options.verbose) {
console.log(`[11ty/eleventy-fetch] ${message}`);
} else {
debug(message);
}
}

get url() {
return this._url;
}
Expand All @@ -63,13 +55,13 @@ class RemoteAssetCache extends AssetCache {
// Important: no disk writes when dryRun
// As of Fetch v4, reads are now allowed!
if(super.isCacheValid(duration) ) {
this.log( `Using cached version of: ${this.displayUrl}` );
this.log( `Cache hit for ${this.displayUrl}` );
return super.getCachedValue();
}

try {
let isDryRun = optionsOverride.dryRun || this.options.dryRun;
this.log( `${isDryRun? "Fetching" : "Caching"}: ${this.displayUrl}` );
this.log( `${isDryRun? "Fetching" : "Cache miss for"} ${this.displayUrl}`);

let fetchOptions = optionsOverride.fetchOptions || this.options.fetchOptions || {};
let response = await fetch(this.url, fetchOptions);
Expand Down

0 comments on commit 2361777

Please sign in to comment.