Skip to content

Commit

Permalink
feat: adding getSync for nonBlocking instances (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
Farenheith authored Nov 8, 2022
1 parent 00759b1 commit 84405a6
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 6 deletions.
31 changes: 25 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 13 additions & 0 deletions src/remembered.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,19 @@ export class Remembered {
return this.blockingGet(key, callback, noCacheIf);
}

getSync<T>(
key: string,
callback: () => PromiseLike<T>,
noCacheIf?: (result: T) => boolean,
): T | undefined {
if (!this.config.nonBlocking) {
throw new Error('getSync is only available for nonBlocking instances');
}
dontWait(() => this.blockingGet(key, callback, noCacheIf));

return this.nonBlockingMap.get(key);
}

blockingGet<T>(
key: string,
callback: () => PromiseLike<T>,
Expand Down
61 changes: 61 additions & 0 deletions test/unit/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,67 @@ describe(Remembered.name, () => {
});
});

describe(methods.getSync, () => {
it('should return cache result when it exists', async () => {
const target2 = new Remembered({
ttl: 2,
nonBlocking: true,
});
let i = 0;
const callback = jest.fn().mockImplementation(() => i++);

const result1 = await target2.get('a', callback);
await delay(3);
const result2 = target2.getSync('a', callback);

expect(result1).toBe(result2);
expectCallsLike(callback, []);
await delay(1);
expectCallsLike(callback, [], []);
const result3 = await target2.get('a', callback);
expect(result3).toBe(1);
expectCallsLike(callback, [], []);
await delay(1);
expectCallsLike(callback, [], []);
});

it('should return undefined when no cache exists, but return something after it is warmed up', async () => {
const target2 = new Remembered({
ttl: 2,
nonBlocking: true,
});
let i = 0;
const callback = jest.fn().mockImplementation(() => i++);

const result1 = target2.getSync('a', callback);

expect(result1).toBeUndefined();
expectCallsLike(callback);
await delay(1);
expectCallsLike(callback, []);
const result2 = target2.getSync('a', callback);
expect(result2).toBe(0);
});

it('should throw an error when nonBlocking is false', async () => {
const target2 = new Remembered({
ttl: 2,
nonBlocking: false,
});
let i = 0;
const callback = jest.fn().mockImplementation(() => i++);
let err: any;

try {
target2.getSync('a', callback);
} catch (error) {
err = error;
}

expect(err).toBeInstanceOf(Error);
});
});

describe(methods.wrap, () => {
it('should return a rememberable callback', async () => {
let count = 0;
Expand Down

0 comments on commit 84405a6

Please sign in to comment.