Add per-field cache invalidation

Summary:
Jest needs this for efficient caching of resolution responses.

public

Reviewed By: voideanvalue

Differential Revision: D2873291

fb-gh-sync-id: fee27d2ffdfe64bd68fdb4d9e4259e721b33631f
This commit is contained in:
Christoph Pojer 2016-01-31 23:24:39 -08:00 committed by facebook-github-bot-9
parent 6891e98578
commit f51d9718da
3 changed files with 38 additions and 5 deletions

View File

@ -303,4 +303,33 @@ describe('Cache', () => {
}); });
}); });
}); });
describe('invalidate', () => {
it('invalidates the cache per file or per-field', () => {
fs.stat.mockImpl((file, callback) =>
callback(null, {
mtime: {
getTime: () => {},
},
})
);
var cache = new Cache({
cacheKey: 'cache',
});
var loaderCb = jest.genMockFn().mockImpl(() =>
Promise.resolve('banana')
);
var file = '/rootDir/someFile';
return cache.get(file, 'field', loaderCb).then(() => {
expect(cache.has(file)).toBe(true);
cache.invalidate(file, 'field');
expect(cache.has(file)).toBe(true);
expect(cache.has(file, 'field')).toBe(false);
cache.invalidate(file);
expect(cache.has(file)).toBe(false);
});
});
});
}); });

View File

@ -58,9 +58,13 @@ class Cache {
return recordP.then(record => record); return recordP.then(record => record);
} }
invalidate(filepath) { invalidate(filepath, field) {
if (this.has(filepath)) { if (this.has(filepath, field)) {
if (field == null) {
delete this._data[filepath]; delete this._data[filepath];
} else {
delete this._data[filepath].data[field];
}
} }
} }
@ -70,7 +74,7 @@ class Cache {
has(filepath, field) { has(filepath, field) {
return Object.prototype.hasOwnProperty.call(this._data, filepath) && return Object.prototype.hasOwnProperty.call(this._data, filepath) &&
(!field || Object.prototype.hasOwnProperty.call(this._data[filepath].data, field)); (field == null || Object.prototype.hasOwnProperty.call(this._data[filepath].data, field));
} }
_set(filepath, field, loaderPromise) { _set(filepath, field, loaderPromise) {

View File

@ -59,7 +59,7 @@ class DependencyGraph {
mocksPattern, mocksPattern,
extractRequires, extractRequires,
shouldThrowOnUnresolvedErrors, shouldThrowOnUnresolvedErrors,
transformCode transformCode,
}; };
this._cache = cache; this._cache = cache;
this._helpers = new DependencyGraphHelpers(this._opts); this._helpers = new DependencyGraphHelpers(this._opts);