Skip to content

Instantly share code, notes, and snippets.

@tomcant
Last active April 5, 2024 08:03
Show Gist options
  • Save tomcant/12c4597e51e171ede8e7d639d803a245 to your computer and use it in GitHub Desktop.
Save tomcant/12c4597e51e171ede8e7d639d803a245 to your computer and use it in GitHub Desktop.
Fastly Cache Warmer
'use strict';
['START_URL', 'PATH_REGEX'].forEach((env) => {
if (!(env in process.env)) {
console.error(`The '${env}' environment variable is missing.`);
process.exit(1);
}
});
let SimpleCrawler = require('simplecrawler');
let crawler = new SimpleCrawler(process.env.START_URL);
let padString = (n, c, p = 6) => (Array(p).join(c) + n).substr(('' + n).length);
let hitOrMissSummary = { HIT: 0, MISS: 0 };
crawler.on('fetchcomplete', (queueItem, _responseBuffer, response) => {
crawler.queue.countItems({ fetched: true }, (err, count) => {
if (err) {
throw err;
}
crawler.queue.getLength((err, length) => {
if (err) {
throw err;
}
let hitOrMiss = response.headers['x-cache'];
hitOrMissSummary[hitOrMiss] += 1;
console.log(
'(%s/%s) X-Cache: %s, Status: %d, Path: %s',
padString(count, '0'),
padString(length, '0'),
padString(hitOrMiss, ' ', 5),
queueItem.stateData.code,
queueItem.path
);
});
});
});
crawler.addFetchCondition((item) => {
return item.path.match(new RegExp(process.env.PATH_REGEX));
});
crawler.on('complete', () => {
console.log(hitOrMissSummary);
});
crawler.start();
{
"name": "fastly-cache-warmer",
"version": "0.0.1",
"author": "Tom Cant <[email protected]>",
"dependencies": {
"simplecrawler": "^1.1.8"
}
}