{"id":20497088,"url":"https://github.com/alexcambose/custom-cache-decorator","last_synced_at":"2025-04-13T18:21:58.509Z","repository":{"id":244582453,"uuid":"815663800","full_name":"alexcambose/custom-cache-decorator","owner":"alexcambose","description":"A TypeScript library providing a customizable cache decorator for methods. This library allows you to easily cache method results with configurable caching mechanisms.","archived":false,"fork":false,"pushed_at":"2024-06-18T17:36:04.000Z","size":495,"stargazers_count":40,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-21T19:49:53.809Z","etag":null,"topics":["cache","library","lru-cache","nodejs","redis","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/alexcambose.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-06-15T19:04:59.000Z","updated_at":"2025-01-20T06:12:08.000Z","dependencies_parsed_at":"2024-06-18T22:10:35.176Z","dependency_job_id":null,"html_url":"https://github.com/alexcambose/custom-cache-decorator","commit_stats":null,"previous_names":["alexcambose/cache-decorator"],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alexcambose%2Fcustom-cache-decorator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alexcambose%2Fcustom-cache-decorator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alexcambose%2Fcustom-cache-decorator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alexcambose%2Fcustom-cache-decorator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/alexcambose","download_url":"https://codeload.github.com/alexcambose/custom-cache-decorator/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248759133,"owners_count":21157095,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cache","library","lru-cache","nodejs","redis","typescript"],"created_at":"2024-11-15T18:09:56.057Z","updated_at":"2025-04-13T18:21:58.466Z","avatar_url":"https://github.com/alexcambose.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Cache Decorator\n\nA TypeScript library providing a customizable cache decorator for methods. This library allows you to easily cache method results with configurable caching mechanisms.\n\n## Installation\n\nInstall the library via npm:\n\n```\nnpm install custom-cache-decorator\n```\n\nor yarn\n\n```\nyarn add custom-cache-decorator\n```\n\n## Usage\n\n### Basic Usage\n\nHere's a basic example of how to use the cache decorator in your TypeScript project.\n\n#### 1. Import the Library\n\n```ts\nimport { createCacheDecorator } from 'custom-cache-decorator';\n```\n\n#### 2. Define Your Cache Decorator\n\nCreate a cache decorator with custom `getItem` and `setItem` functions:\n\n```ts\nimport { createCacheDecorator } from 'custom-cache-decorator';\n\nconst inMemoryCache = new Map\u003cstring, any\u003e();\n\nconst cacheDecorator = createCacheDecorator({\n  getItem: async (key) =\u003e inMemoryCache.get(key),\n  setItem: async (key, value) =\u003e inMemoryCache.set(key, value),\n});\n```\n\n#### 3. Apply the Cache Decorator\n\nUse the created cache decorator on your methods:\n\n```ts\nclass ExpensiveOperations {\n  @cacheDecorator({ ttl: 3000 })\n  async heavyComputation(arg1: number, arg2: number): Promise\u003cnumber\u003e {\n    console.log('Performing heavy computation...');\n    // Simulate heavy computation\n    return new Promise((resolve) =\u003e\n      setTimeout(() =\u003e resolve(arg1 * arg2), 1000)\n    );\n  }\n}\n```\n\n#### 4. Use Your Class\n\n```ts\n(async () =\u003e {\n  const operations = new ExpensiveOperations();\n\n  console.log(await operations.heavyComputation(2, 3)); // Performs computation\n  console.log(await operations.heavyComputation(2, 3)); // Uses cached result\n})();\n```\n\nalso make sure you have `experimentalDecorators` set to `true` in your `tsconfig.json` file\n```\n{\n  \"compilerOptions\": {\n    ...\n    \"experimentalDecorators\": true\n    ...\n  }\n}\n```\n### Using with Redis\n\nHere's an example of using the cache decorator with Redis as the caching backend.\n\n```ts\nimport { createCacheDecorator } from 'custom-cache-decorator';\nimport { createClient } from 'redis';\n\n(async () =\u003e {\n  const client = createClient();\n  await client.connect();\n\n  const redisCacheDecorator = createCacheDecorator({\n    getItem: async (key) =\u003e {\n      const value = await client.get(key);\n      return value ? JSON.parse(value) : undefined;\n    },\n    setItem: async (key, value, { ttl }: { ttl: number }) =\u003e {\n      await client.setEx(key, ttl, JSON.stringify(value));\n    },\n  });\n\n  class ExpensiveOperations {\n    @redisCacheDecorator({ ttl: 60 })\n    async heavyComputation(arg1: number, arg2: number): Promise\u003cnumber\u003e {\n      console.log('Performing heavy computation...');\n      // Simulate heavy computation\n      return new Promise((resolve) =\u003e\n        setTimeout(() =\u003e resolve(arg1 * arg2), 1000)\n      );\n    }\n  }\n\n  const operations = new ExpensiveOperations();\n\n  console.log(await operations.heavyComputation(2, 3)); // Performs computation\n  console.log(await operations.heavyComputation(2, 3)); // Uses cached result\n\n  await client.disconnect();\n})();\n```\n\n## API\n\n### `createCacheDecorator(options: CreateCacheDecoratorOptions\u003cT, O\u003e): (decoratorArgs: O) =\u003e MethodDecorator`\n\nCreates a cache decorator.\n\n#### Parameters\n\n- `options`: Configuration options for the cache decorator.\n  - `getItem`: Function to retrieve an item from the cache.\n  - `setItem`: Function to store an item in the cache.\n  - `generateKey` (optional): Custom function to generate cache keys. Defaults to `defaultGenerateKey`.\n\n#### Returns\n\nA cache decorator function to be applied to class methods.\n\n### `defaultGenerateKey(className: string, methodName: string, args: unknown[]): string`\n\nDefault function to generate cache keys.\n\n#### Parameters\n\n- `className`: The name of the class.\n- `methodName`: The name of the method.\n- `args`: The arguments passed to the method.\n\n#### Returns\n\nA string representing the cache key.\n\n### Advanced Example with Custom Key Generation\n\nYou can customize the cache key generation with the `generateKey` arg.\n\n```ts\nimport {\n  createCacheDecorator,\n  defaultGenerateKey,\n} from 'custom-cache-decorator';\n\nconst customKeyDecorator = createCacheDecorator({\n  getItem: async (key) =\u003e inMemoryCache.get(key),\n  setItem: async (key, value) =\u003e inMemoryCache.set(key, value),\n  generateKey: (className, methodName, args) =\u003e\n    `${className}_${methodName}_${args.join('_')}`,\n});\n\nclass ExpensiveOperations {\n  @customKeyDecorator({})\n  async heavyComputation(arg1: number, arg2: number): Promise\u003cnumber\u003e {\n    console.log('Performing heavy computation...');\n    return new Promise((resolve) =\u003e\n      setTimeout(() =\u003e resolve(arg1 * arg2), 1000)\n    );\n  }\n}\n```\n\n## Contributing\n\nContributions are welcome! Please open an issue or submit a pull request on GitHub.\n\n## License\n\nThis project is licensed under the MIT License.\n\n:star:\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falexcambose%2Fcustom-cache-decorator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falexcambose%2Fcustom-cache-decorator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falexcambose%2Fcustom-cache-decorator/lists"}