Skip to content

Commit

Permalink
fix: don't cache empty results, added test
Browse files Browse the repository at this point in the history
  • Loading branch information
ErikBjare committed Nov 15, 2023
1 parent b7ee73a commit 4fdeb16
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/aw-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export class AWClient {

public controller: AbortController;

private queryCache: { [cacheKey: string]: object };
private queryCache: { [cacheKey: string]: object[] };
private heartbeatQueues: {
[bucketId: string]: {
isProcessing: boolean;
Expand Down Expand Up @@ -316,7 +316,10 @@ export class AWClient {
public async query(
timeperiods: (string | { start: Date; end: Date })[],
query: string[],
params: { cache?: boolean } = { cache: true },
params: { cache?: boolean; cacheEmpty?: boolean } = {
cache: true,
cacheEmpty: false,
},
): Promise<any[]> {
const data = {
query,
Expand All @@ -340,7 +343,10 @@ export class AWClient {
}
// check cache
const cacheKey = JSON.stringify({ timeperiod, query });
if (this.queryCache[cacheKey]) {
if (
this.queryCache[cacheKey] &&
(params.cacheEmpty || this.queryCache[cacheKey].length > 0)
) {
cacheResults.push(this.queryCache[cacheKey]);
} else {
cacheResults.push(null);
Expand Down
21 changes: 21 additions & 0 deletions src/test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,27 @@ describe("Basic API usage", () => {
const resp3: IEvent[][] = await awc.query(timeperiods2, query);
assert.equal(2, resp3[0].length);
assert.equal(2, resp3[1].length);

// Query a timeperiod without events in the past,
// then add an event for the timeperiod, and query again.
// This is to check that we don't cache when the query returned nothing.
const timeperiods3 = [
{ start: new Date("1980-1-1"), end: new Date("1980-1-2") },
];
const resp4: IEvent[][] = await awc.query(timeperiods3, query);

// Check that the result is empty
assert.equal(0, resp4[0].length);

// Add an event for the timeperiod
await awc.heartbeat(bucketId, 5, {
...testevent,
timestamp: new Date("1980-1-1"),
});

// Query again and check that the result is not empty
const resp5: IEvent[][] = await awc.query(timeperiods3, query);
assert.equal(1, resp5[0].length);
});
});

Expand Down

0 comments on commit 4fdeb16

Please sign in to comment.