Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/codecov.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,5 @@ jobs:
./packages/flat-cache/coverage/lcov.info, \
./packages/node-cache/coverage/lcov.info, \
./packages/memoize/coverage/lcov.info, \
./packages/memory/coverage/lcov.info, \
./packages/utils/coverage/lcov.info
2 changes: 1 addition & 1 deletion packages/benchmark/memory-lru.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createBenchmark, getModuleName, printToConsole, generateAlphaNumeric } from "index.js";
import { CacheableMemory } from "cacheable";
import { CacheableMemory } from "@cacheable/memory";
import QuickLRU from 'quick-lru';
import { createLRU } from 'lru.min';

Expand Down
4 changes: 2 additions & 2 deletions packages/benchmark/memory.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { createBenchmark, getModuleName, printToConsole, generateAlphaNumeric } from "index.js";
import { CacheableMemory } from "cacheable";
import { CacheableMemory } from "@cacheable/memory";
import NodeCache from 'node-cache';
import { BentoCache, bentostore } from 'bentocache';
import { memoryDriver } from 'bentocache/drivers/memory';

const bench = createBenchmark("Memory Benchmark", 100000);

// Cacheable Memory
const cacheable = new CacheableMemory();
const cacheable = new CacheableMemory({storeHashSize: 1});
let cacheableName = getModuleName("Cacheable Memory", "1.10.0");

// Node Cache
Expand Down
1 change: 1 addition & 0 deletions packages/benchmark/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"bentocache": "^1.4.0",
"cache-manager": "workspace:^",
"cacheable": "workspace:^",
"@cacheable/memory": "workspace:^",
"lru.min": "^1.1.2",
"quick-lru": "^7.0.1",
"tinybench": "^4.0.1"
Expand Down
1 change: 0 additions & 1 deletion packages/memoize/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
"@types/eslint": "^9.6.1",
"@types/node": "^24.1.0",
"@vitest/coverage-v8": "^3.2.4",
"cacheable": "workspace:^",
"lru-cache": "^11.1.0",
"rimraf": "^6.0.1",
"tsup": "^8.5.0",
Expand Down
29 changes: 22 additions & 7 deletions packages/memoize/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import {hash, coalesceAsync} from '@cacheable/utils';
import type {Cacheable, CacheableMemory} from 'cacheable';

export type CacheInstance = {
get: (key: string) => Promise<any | undefined>;
has: (key: string) => Promise<boolean>;
set: (key: string, value: any, ttl?: number | string) => Promise<void>;
on: (event: string, listener: (...args: any[]) => void) => void;
emit: (event: string, ...args: any[]) => boolean;
};

export type CacheSyncInstance = {
get: (key: string) => any | undefined;
has: (key: string) => boolean;
set: (key: string, value: any, ttl?: number | string) => void;
on: (event: string, listener: (...args: any[]) => void) => void;
emit: (event: string, ...args: any[]) => boolean;
};

export type GetOrSetKey = string | ((options?: GetOrSetOptions) => string);

Expand All @@ -11,7 +26,7 @@ export type GetOrSetFunctionOptions = {

export type GetOrSetOptions = GetOrSetFunctionOptions & {
cacheId?: string;
cache: Cacheable;
cache: CacheInstance;
};

export type CreateWrapKey = (function_: AnyFunction, arguments_: any[], options?: WrapFunctionOptions) => string;
Expand All @@ -25,11 +40,11 @@ export type WrapFunctionOptions = {
};

export type WrapOptions = WrapFunctionOptions & {
cache: Cacheable;
cache: CacheInstance;
};

export type WrapSyncOptions = WrapFunctionOptions & {
cache: CacheableMemory;
cache: CacheSyncInstance;
};

export type AnyFunction = (...arguments_: any[]) => any;
Expand All @@ -43,12 +58,12 @@ export function wrapSync<T>(function_: AnyFunction, options: WrapSyncOptions): A
cacheKey = options.createKey(function_, arguments_, options);
}

let value = cache.get(cacheKey);
let value = cache.get(cacheKey) as T | undefined;

if (value === undefined) {
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
value = function_(...arguments_);
value = function_(...arguments_) as T;
cache.set(cacheKey, value, ttl);
} catch (error) {
cache.emit('error', error);
Expand Down Expand Up @@ -101,7 +116,7 @@ export function wrap<T>(function_: AnyFunction, options: WrapOptions): AnyFuncti
}

// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-return
return cache.getOrSet(cacheKey, async (): Promise<T | undefined> => function_(...arguments_), options);
return getOrSet(cacheKey, async (): Promise<T | undefined> => function_(...arguments_), options);
};
}

Expand Down
12 changes: 6 additions & 6 deletions packages/memoize/test/get-or-set.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import {
describe, test, expect, vi,
} from 'vitest';
import {Cacheable} from 'cacheable';
import {getOrSet, type GetOrSetOptions} from '../src/index.js';
import {MockCacheable, MockCacheableMemory} from './mock-cacheable.js';

describe('cacheable get or set', () => {
test('should cache results', async () => {
const cacheable = new Cacheable();
const cacheable = new MockCacheable();
const function_ = vi.fn(async () => 1 + 2);
const result = await getOrSet('one_plus_two', function_, {cache: cacheable});
await getOrSet('one_plus_two', function_, {cache: cacheable});
Expand All @@ -15,7 +15,7 @@ describe('cacheable get or set', () => {
});

test('should prevent stampede', async () => {
const cacheable = new Cacheable();
const cacheable = new MockCacheable();
const function_ = vi.fn(async () => 42);
await Promise.all([
getOrSet('key1', function_, {cache: cacheable}),
Expand All @@ -27,7 +27,7 @@ describe('cacheable get or set', () => {
});

test('should throw on getOrSet error', async () => {
const cacheable = new Cacheable();
const cacheable = new MockCacheable();
const function_ = vi.fn(async () => {
throw new Error('Test error');
});
Expand All @@ -37,7 +37,7 @@ describe('cacheable get or set', () => {
});

test('should throw on getOrSet error with cache errors true', async () => {
const cacheable = new Cacheable();
const cacheable = new MockCacheable();
const function_ = vi.fn(async () => {
throw new Error('Test error');
});
Expand All @@ -47,7 +47,7 @@ describe('cacheable get or set', () => {
});

test('should generate key via function on getOrSet', async () => {
const cacheable = new Cacheable();
const cacheable = new MockCacheable();
const generateKey = (options?: GetOrSetOptions) => `custom_key_${options?.cacheId}`;
const function_ = vi.fn(async () => Math.random() * 100);
const result1 = await getOrSet(generateKey, function_, {cache: cacheable});
Expand Down
95 changes: 95 additions & 0 deletions packages/memoize/test/mock-cacheable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import {type CacheableStoreItem} from '@cacheable/utils';
import {type CacheInstance, type CacheSyncInstance} from '../src/index.js';

export class MockCacheable implements CacheInstance {
private readonly cache = new Map<string, CacheableStoreItem>();
private readonly listeners: Record<string, Array<(...args: any[]) => void>> = {};

async get(key: string): Promise<any | undefined> {
const item = this.cache.get(key);
if (item?.expires && Date.now() > item.expires) {
this.cache.delete(key);
return undefined;
}

return item?.value;
}

async has(key: string): Promise<boolean> {
return await this.get(key) !== undefined;
}

async set(key: string, value: any, ttl?: number | string): Promise<void> {
let expires: number | undefined;
if (ttl && typeof ttl === 'number' && ttl > 0) {
expires = Date.now() + ttl;
}

// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this.cache.set(key, {key, value, expires});
}

on(event: string, listener: (...args: any[]) => void): void {
this.listeners[event] ||= [];

this.listeners[event].push(listener);
}

emit(event: string, ...args: any[]): boolean {
const listeners = this.listeners[event];
if (listeners) {
for (const listener of listeners) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
listener(...args);
}
}

return true;
}
}

export class MockCacheableMemory implements CacheSyncInstance {
private readonly cache = new Map<string, CacheableStoreItem>();
private readonly listeners: Record<string, Array<(...args: any[]) => void>> = {};

get(key: string): any | undefined {
const result = this.cache.get(key);
if (result?.expires && Date.now() > result.expires) {
this.cache.delete(key);
return undefined;
}

return result?.value;
}

has(key: string): boolean {
return this.get(key) !== undefined;
}

set(key: string, value: any, ttl?: number | string): void {
let expires: number | undefined;
if (ttl && typeof ttl === 'number' && ttl > 0) {
expires = Date.now() + ttl;
}

// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this.cache.set(key, {key, value, expires});
}

on(event: string, listener: (...args: any[]) => void): void {
this.listeners[event] ||= [];
this.listeners[event].push(listener);
}

emit(event: string, ...args: any[]): boolean {
const listeners = this.listeners[event];
if (listeners) {
for (const listener of listeners) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
listener(...args);
}
}

return true;
}
}
Loading