Skip to content

FileCache: allow custom getCacheKey #41

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions src/FileCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,14 @@ function jsonParse(data: string, cb: (err: Error | null, result?: any) => void):
cb(null, result);
}

function getCacheKey(url: string): string {
const hash = createHash('sha512')
hash.update(url)
return hash.digest('hex')
}

export default class FileCache implements ICache {
private readonly _location: string;
constructor(location: string) {
this._location = location;
}

getResponse(url: string, callback: (err: null | Error, response: null | CachedResponse) => void) {
const key = resolve(this._location, getCacheKey(url));
const key = resolve(this._location, this.getCacheKey(url));

fs.readFile(key + '.json', 'utf8', function (err, data) {
if (err && err.code === 'ENOENT') return callback(null, null);
Expand All @@ -47,7 +41,7 @@ export default class FileCache implements ICache {
}

setResponse(url: string, response: CachedResponse): void {
const key = resolve(this._location, getCacheKey(url));
const key = resolve(this._location, this.getCacheKey(url));
let errored = false;

fs.mkdir(this._location, function (err) {
Expand Down Expand Up @@ -76,7 +70,7 @@ export default class FileCache implements ICache {
}

updateResponseHeaders(url: string, response: Pick<CachedResponse, 'headers' | 'requestTimestamp'>) {
const key = resolve(this._location, getCacheKey(url));
const key = resolve(this._location, this.getCacheKey(url));
fs.readFile(key + '.json', 'utf8', function (err, data) {
if (err) {
console.warn('Error writing to cache: ' + err.message);
Expand All @@ -103,10 +97,16 @@ export default class FileCache implements ICache {
}

invalidateResponse(url: string, callback: (err: NodeJS.ErrnoException | null) => void): void {
const key = resolve(this._location, getCacheKey(url));
const key = resolve(this._location, this.getCacheKey(url));
fs.unlink(key + '.json', (err?: NodeJS.ErrnoException | null) => {
if (err && err.code === 'ENOENT') return callback(null);
else callback(err || null);
});
}

getCacheKey(url: string): string {
const hash = createHash('sha512');
hash.update(url);
return hash.digest('hex');
}
}
30 changes: 29 additions & 1 deletion test/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@

var assert = require('assert');
var request = require('../');
var FileCache = require('../lib/FileCache').default;
var http = require('http');
var serveStatic = require('serve-static');
var rimraf = require('rimraf');
var path = require('path');
var url = require('url');
var qs = require('querystring');

rimraf.sync(path.resolve(__dirname, '..', 'lib', 'cache'));
const cacheDir = path.resolve(__dirname, '..', 'lib', 'cache');
rimraf.sync(cacheDir);


var CACHED_BY_CACHE_CONTROL = 'http://localhost:3293/index.js';
Expand Down Expand Up @@ -297,6 +299,32 @@ lastModifiedServer.listen(5295, function onListen() {
}, 1000);
});
});

const staticKeyCache = new FileCache(cacheDir);
staticKeyCache.getCacheKey = function (res) {
return 'static-key';
};
request('GET', CACHED_BY_CACHE_CONTROL, {cache: staticKeyCache}, function (err, res) {
if (err) throw err;

console.log('response O (populate file cache)');
assert(res.statusCode === 200);
assert(res.fromCache === undefined);
assert(res.fromNotModified === undefined);
res.body.on('data', function () {});
res.body.on('end', function () {
setTimeout(function () {
request('GET', CACHED_BY_CACHE_CONTROL + '?a=b', {cache: staticKeyCache}, function (err, res) {
if (err) throw err;

console.log('response P (from file cache)');
assert(res.statusCode === 200);
assert(res.fromCache === true);
res.body.resume();
});
}, 1000);
});
});
});

lastModifiedServer.unref();