From 1fc652184f084763f3ae2ad1cce12c7c7d103e1c Mon Sep 17 00:00:00 2001 From: vinicius Date: Thu, 8 Aug 2024 17:33:05 -0300 Subject: [PATCH] add decorator / fix docs/readme / add license --- LICENSE | 7 +++++++ README.md | 2 +- src/caches/cache.ts | 8 +++++--- src/caches/decorator.ts | 22 ++++++++++++++++++++++ src/caches/fifo.ts | 5 +++-- src/caches/index.ts | 1 + src/caches/lfu.ts | 5 +++-- src/caches/lru.ts | 5 +++-- src/caches/pool.ts | 5 +++-- src/caches/rrcache.ts | 5 +++-- src/caches/ttl.ts | 7 ++++--- src/index.ts | 5 ++++- src/types/params.ts | 27 ++++++++++++++++++++++----- src/utils/errors.ts | 21 +++++++++++---------- tests/decorator.test.ts | 39 +++++++++++++++++++++++++++++++++++++++ 15 files changed, 131 insertions(+), 33 deletions(-) create mode 100644 LICENSE create mode 100644 src/caches/decorator.ts create mode 100644 tests/decorator.test.ts diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..cc8efea --- /dev/null +++ b/LICENSE @@ -0,0 +1,7 @@ +Copyright 2024 Vinicius Alves + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index a0375e4..1f502fa 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ All of most used cache types are included here, if what you are looking for does //example cache import { TTLCache } from 'cachetools-js' -const cache = TTLCache({ttl: 1000}) +const cache = new TTLCache({ttl: 1000}) ``` #### Store a key in cache ```typescript diff --git a/src/caches/cache.ts b/src/caches/cache.ts index 5a3114a..e2ac9a5 100644 --- a/src/caches/cache.ts +++ b/src/caches/cache.ts @@ -3,9 +3,11 @@ import { CacheParams, Keyable } from '../types' /** * ### About - * Simple cache base class, based in `Proxy` to turn possible to get/set keys like a common object, - * use this class if you want to create a custom cache logic, - * you can use for personal purpose too, but i dont know why + * Simple cache base class, based on `Proxy`, which allows getting and setting keys like a regular object. + * + * This class is useful if you want to create custom cache logic. + * + * It can also be used for personal purposes, although its specific application might not be obvious in all cases. * * ### Example * ```typescript diff --git a/src/caches/decorator.ts b/src/caches/decorator.ts new file mode 100644 index 0000000..5170c1d --- /dev/null +++ b/src/caches/decorator.ts @@ -0,0 +1,22 @@ +import { CacheLike } from '../types' + +export function cacheDecorator + Promise | any> + (fn: T, cache: CacheLike): T { + return async function (...args: Parameters): Promise> { + const key = args.join('.') + + const cachedResult = cache.get(key) + if (cachedResult) { + return cachedResult as ReturnType + } + + const result = await fn(...args) + + if (cache) { + cache.set(key, result) + } + + return result + } as T +} diff --git a/src/caches/fifo.ts b/src/caches/fifo.ts index 47eece1..6c421d6 100644 --- a/src/caches/fifo.ts +++ b/src/caches/fifo.ts @@ -4,8 +4,9 @@ import { MissingSize } from '../utils' /** * ### About - * This cache remove values based in **FIFO (First In, First Out)**, - * when cache is full, will remove the first key stored + * This cache remove values based in **FIFO (First In, First Out)**. + * + * When the cache is full, it will remove the first key that was stored. * * ### Example * ```typescript diff --git a/src/caches/index.ts b/src/caches/index.ts index 1761e02..b57bc62 100644 --- a/src/caches/index.ts +++ b/src/caches/index.ts @@ -5,3 +5,4 @@ export * from './fifo' export * from './lfu' export * from './rrcache' export * from './pool' +export * from './decorator' diff --git a/src/caches/lfu.ts b/src/caches/lfu.ts index fb09b66..02c5723 100644 --- a/src/caches/lfu.ts +++ b/src/caches/lfu.ts @@ -4,8 +4,9 @@ import { MissingSize } from '../utils' /** * ### About - * This cache remove values based in **LFU (Least Frequently Used)**, - * when cache is full, will remove the key less used + * This cache removes values based on **LFU (Least Frequently Used)**. + * + * When the cache is full, it will remove the least frequently used key. * * ### Example * ```typescript diff --git a/src/caches/lru.ts b/src/caches/lru.ts index 4b7b489..5ea96b9 100644 --- a/src/caches/lru.ts +++ b/src/caches/lru.ts @@ -4,8 +4,9 @@ import { MissingSize } from '../utils' /** * ### About - * This cache remove values based in **LRU (Least Recently Used)**, - * when cache is full, will remove the less recently used key + * This cache removes values based on **LRU (Least Recently Used)**. + * + * When the cache is full, it will remove the least recently used key. * * ### Example * ```typescript diff --git a/src/caches/pool.ts b/src/caches/pool.ts index c281861..ad2cdf9 100644 --- a/src/caches/pool.ts +++ b/src/caches/pool.ts @@ -3,8 +3,9 @@ import { CacheLike, CachePoolParams, CachesObj, CacheTypes, Keyable, ParamsLike /** * ### About - * Pool of caches to store all your caches in a unique variable, making your code more cleaner and easier, - * you can create/get/delete all types of caches, and use standard methods from caches more simplier + * Pool of caches to store all your caches in a single variable, making your code cleaner and easier to manage. + * + * You can create, get, and delete all types of caches, using standard cache methods more simply. * * ### Example * ```typescript diff --git a/src/caches/rrcache.ts b/src/caches/rrcache.ts index 9588d09..8568850 100644 --- a/src/caches/rrcache.ts +++ b/src/caches/rrcache.ts @@ -4,8 +4,9 @@ import { MissingSize } from '../utils' /** * ### About - * This cache remove values based in **Random Logic**, - * when cache is full, a random key will be removed based in random logic provided + * This cache removes values based on **Random Logic**. + * + * When the cache is full, a random key will be removed according to the provided random logic. * * ### Example * ```typescript diff --git a/src/caches/ttl.ts b/src/caches/ttl.ts index 9211201..cfb638c 100644 --- a/src/caches/ttl.ts +++ b/src/caches/ttl.ts @@ -4,8 +4,9 @@ import { SizeError } from '../utils' /** * ### About - * This cache remove values based in TTL (Time-To-Live), - * if you store a key with TTL of 1 second, in 1 second this key will be removed. + * This cache removes values based on TTL (Time-To-Live). + * + * If you store a key with a TTL of 1 second, that key will be removed after 1 second. * * ### Example * ```typescript @@ -18,7 +19,7 @@ import { SizeError } from '../utils' * * //custom ttl will be used (500) * cache.set('bar', 'foo', 500) - * + * * //store another key * cache['baz'] = 'foo' * //throws SizeError, you need to delete some key to store another key diff --git a/src/index.ts b/src/index.ts index a8c1422..3e7ee83 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,5 +3,8 @@ export * from './types' export { SizeError, - MissingSize + MissingSize, + AlreadyExists, + CacheNotExists, + CacheTypeNotExists } from './utils' diff --git a/src/types/params.ts b/src/types/params.ts index b13298e..ca27304 100644 --- a/src/types/params.ts +++ b/src/types/params.ts @@ -1,23 +1,40 @@ export interface CacheParams { - /**Defines the max quantity of keys that will be stored, in some caches this param is required, default is `undefined` */ + /** + * Defines the maximum number of keys that will be stored. + * In some caches, this parameter is required; the default is `undefined`. + */ maxsize?: number - /**If true, will create a **deep copy** of all data before store, default is `false` */ + + /** + * If true, a **deep copy** of all data will be created before storing. + * The default is `false`. + */ useClones?: boolean } export interface TTLParams extends CacheParams { - /** It's the **Time to Live** of cache in **ms**, if you dont provide `ttl` param in `set` function, this ttl will be used, if not provided, the cache will not delete keys */ + /** + * The **Time to Live** of the cache in **ms**. + * If you don't provide the `ttl` parameter in the `set` function, this `ttl` will be used. + * If not provided, the cache will not delete keys. + */ ttl?: number } export interface RRParams extends CacheParams { - /**Random logic for deletion of keys in cache, default is `Math.floor(Math.random * length)` */ + /** + * Random logic for the deletion of keys in the cache. + * The default is `Math.floor(Math.random() * length)`. + */ randomLogic?: (length: number) => number } export type ParamsLike = CacheParams | TTLParams | RRParams export interface CachePoolParams { - /**Defines the max quantity of caches that will be stored, this param is optional, default is `undefined` */ + /** + * Defines the maximum number of caches that will be stored. + * This parameter is optional; the default is `undefined`. + */ maxsize?: number } diff --git a/src/utils/errors.ts b/src/utils/errors.ts index 7018f01..83b38b8 100644 --- a/src/utils/errors.ts +++ b/src/utils/errors.ts @@ -1,29 +1,30 @@ export class SizeError extends Error { - constructor(){ - super('Tried to set key in cache or pool that is full') + constructor() { + super('Attempted to set a key in a cache or pool that is full.') } } export class MissingSize extends Error { - constructor(){ - super('The maxsize param need to be passed in this cache type') + constructor() { + super('The `maxsize` parameter must be provided for this cache type.') } } export class CacheNotExists extends Error { - constructor(){ - super('Tried to access cache that not exists in a pool') + constructor() { + super('Attempted to access a cache that does not exist in the pool.') } } export class CacheTypeNotExists extends Error { - constructor(){ - super('Cache type passed to \'createCache\' not exists') + constructor() { + super('The cache type passed to `createCache` does not exist.') } } export class AlreadyExists extends Error { - constructor(){ - super('This cache already exists') + constructor() { + super('This cache already exists.') } } + diff --git a/tests/decorator.test.ts b/tests/decorator.test.ts new file mode 100644 index 0000000..46654e2 --- /dev/null +++ b/tests/decorator.test.ts @@ -0,0 +1,39 @@ +import { Cache, cacheDecorator, CacheLike } from '../src' + +describe('Decorator', () => { + let fn: (...args: number[]) => number + let cache: CacheLike + let cachedFunc: (...args: number[]) => number + + beforeEach(() => { + fn = (...args) => args.reduce((p, c) => p + c) + cache = new Cache({maxsize: 10}) + cachedFunc = cacheDecorator(fn, cache) + }) + + test('should get a cached value', async () => { + //store a value + await cachedFunc(1, 2, 3) + + //get a value + expect( + cache['1.2.3'] + ).toBe(6) + + //use a value + await cachedFunc(1, 2, 3) + + //store new value + await cachedFunc(1, 2, 3, 4) + + //get a value + expect( + cache['1.2.3.4'] + ).toBe(10) + + //check cache length -- 2 values + expect( + cache.length() + ).toBe(2) + }) +}) \ No newline at end of file