Skip to content

Commit

Permalink
Fixed Date Entry and fixed that the Prune Callback did not got called…
Browse files Browse the repository at this point in the history
… on peek deletion
  • Loading branch information
Duell10111 committed Jul 12, 2021
1 parent fed87b3 commit 4c44c9b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
24 changes: 24 additions & 0 deletions src/cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ const cache = new Cache({
backend: MemoryStore
});

function Sleep(milliseconds : number) {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}

describe("cache", () => {
it("can set and get entry", async () => {
await cache.set("key1", "value1");
Expand Down Expand Up @@ -75,4 +79,24 @@ describe("cache", () => {

expect(Object.keys(entries).length).toBe(0);
});

it("can get notified when element got deleted", async () => {
let lastprunekeys : string[] = []
const testCache = new Cache({
backend: MemoryStore,
namespace: "ntest",
policy: {
maxEntries: 1,
stdTTL: 1,
},
prunecallback: (keys) => lastprunekeys = keys
})
await testCache.set("key", "value")
const value = await testCache.peek("key")

expect(value).toBe("value")
await Sleep(1000)
expect(await testCache.peek("key")).toBeUndefined()
expect(lastprunekeys[0]).toBe("key")
})
});
16 changes: 12 additions & 4 deletions src/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ export interface ICachePolicy {
stdTTL: number; // second
}

interface Entry {
created : number
value : string
}

export default class Cache {
protected backend: any;
protected namespace: string;
Expand Down Expand Up @@ -101,7 +106,7 @@ export default class Cache {
const compositeKey = this.makeCompositeKey(key);
const entryJsonString = await this.backend.getItem(compositeKey);

let entry;
let entry : Entry | undefined;
if (entryJsonString) {
entry = JSON.parse(entryJsonString);
}
Expand All @@ -110,9 +115,12 @@ export default class Cache {
if (entry) {
value = entry.value;
if (this.policy.stdTTL > 0) {
const deadline = entry.created.getTime() + this.policy.stdTTL * 1000;
const deadline = entry.created + this.policy.stdTTL * 1000;
const now = Date.now();
if (deadline < now) {
if(this.prunecallback) {
this.prunecallback([key])
}
this.remove(key);
value = undefined;
}
Expand All @@ -130,8 +138,8 @@ export default class Cache {
}

public async set(key: string, value: string): Promise<void> {
const entry = {
created: new Date(),
const entry : Entry = {
created: Date.now(),
value
};

Expand Down

0 comments on commit 4c44c9b

Please sign in to comment.