Skip to content

Commit

Permalink
Feature: Support no-cache requests (#21)
Browse files Browse the repository at this point in the history
* code cleanup

* require url

* no mjml

* code cleanup

* fixed tests, rm sinon, ported mocks to jest

* port chai assert -> jest expect

* bump dependencies

* renamed client.server -> client.connection

* prettier code-style

* skip cache is $nocache is specified in requestData
  • Loading branch information
swellmike authored Sep 18, 2023
1 parent 68f20b2 commit b7dd15c
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
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

0 comments on commit b7dd15c

Please sign in to comment.