Skip to content
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

Feature: Support no-cache requests #21

Merged
merged 11 commits into from
Sep 18, 2023
5 changes: 4 additions & 1 deletion lib/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,10 @@ class Client extends EventEmitter {
});
}

if (this.cache && this.sentVersions) {
// Indicates whether to check the request cache or not
const isRequestCacheable = data?.$nocache === undefined;

if (this.cache && this.sentVersions && isRequestCacheable) {
const cacheResult = this.cache.get(url, data);
if (cacheResult?.$data !== undefined) {
return new Promise((resolve) => {
Expand Down
37 changes: 37 additions & 0 deletions lib/client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,7 @@ describe('Client', () => {
client.authed = true;
client.sentVersions = true;

// simulate a cache hit
getCacheStub = jest
.spyOn(Cache.prototype, 'get')
.mockImplementation(() => {
Expand Down Expand Up @@ -586,6 +587,42 @@ describe('Client', () => {
expect(response).toEqual(returnValue);
expect(headers).toEqual({ $data: returnValue });
});

it('returns the cached response on cache hit', async () => {
const result = await client.get('url', 'data');

expect(result).toEqual(returnValue);
expect(getCacheStub).toHaveBeenCalledTimes(1);
expect(getCacheStub).toHaveBeenCalledWith('url', 'data');
expect(requestStub).not.toHaveBeenCalled();
});

it('sends a request on cache miss', async () => {
// simulate a cache miss
getCacheStub.mockImplementationOnce(() => {
return null;
});

await client.get('url', 'data');

expect(getCacheStub).toHaveBeenCalledTimes(1);
expect(getCacheStub).toHaveBeenCalledWith('url', 'data');
expect(requestStub).toHaveBeenCalledTimes(1);
expect(requestStub).toHaveBeenCalledWith('get', 'url', 'data', undefined);
});

it('skips the cache if $nocache is specified', async () => {
await client.get('url', { $nocache: true });

expect(getCacheStub).not.toHaveBeenCalled();
expect(requestStub).toHaveBeenCalledTimes(1);
expect(requestStub).toHaveBeenCalledWith(
'get',
'url',
{ $nocache: true },
undefined
);
});
});
});

Expand Down