{"id":20465126,"url":"https://github.com/pierreduc/ts-method-cache","last_synced_at":"2025-04-13T08:42:55.098Z","repository":{"id":47337474,"uuid":"92482004","full_name":"PierreDuc/ts-method-cache","owner":"PierreDuc","description":"Method cache using decorators for TypeScript","archived":false,"fork":false,"pushed_at":"2023-04-25T10:07:00.000Z","size":182,"stargazers_count":18,"open_issues_count":2,"forks_count":4,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-11T01:42:09.991Z","etag":null,"topics":["cache","decorators","localstorage","memory-cache","sessionstorage","typescript"],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/PierreDuc.png","metadata":{"files":{"readme":"README.md","changelog":null,"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":"2017-05-26T07:01:26.000Z","updated_at":"2023-02-16T17:43:36.000Z","dependencies_parsed_at":"2024-06-19T00:02:03.225Z","dependency_job_id":"d6a97ebb-6168-47e7-af5b-f474e31dbb5a","html_url":"https://github.com/PierreDuc/ts-method-cache","commit_stats":{"total_commits":33,"total_committers":2,"mean_commits":16.5,"dds":"0.030303030303030276","last_synced_commit":"588d9156f95577b492e7595a8db55afba45b0016"},"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PierreDuc%2Fts-method-cache","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PierreDuc%2Fts-method-cache/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PierreDuc%2Fts-method-cache/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PierreDuc%2Fts-method-cache/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/PierreDuc","download_url":"https://codeload.github.com/PierreDuc/ts-method-cache/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248687546,"owners_count":21145735,"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","decorators","localstorage","memory-cache","sessionstorage","typescript"],"created_at":"2024-11-15T13:17:22.914Z","updated_at":"2025-04-13T08:42:55.035Z","avatar_url":"https://github.com/PierreDuc.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![npm](https://img.shields.io/npm/v/ts-method-cache.svg)](https://www.npmjs.com/package/ts-method-cache)\n[![Build Status](https://travis-ci.org/PierreDuc/ts-method-cache.svg?branch=master)](https://travis-ci.org/PierreDuc/ts-method-cache)\n[![codecov](https://codecov.io/gh/PierreDuc/ts-method-cache/branch/master/graph/badge.svg)](https://codecov.io/gh/PierreDuc/ts-method-cache)\n\n# TypeScript Method Cache\n\nMethod cache using decorators for TypeScript. This comes in handy for a quick and easy to implement caching mechanism\nfor obtaining static data from an API or other databases.\n\nThe current storage methods are:\n\n-   Memory Cache _clears after browser refresh or restart_\n-   Session Cache _clears after closing the browser (cannot be used inside node, acts like `MemoryCache` if used in node)_\n-   Storage Cache _clears after clearing the storage (cannot be used inside node, acts like `MemoryCache` if used in node)_\n\n## Prerequisites\n\nEnable `experimentalDecorators` in your `tsconfig.json`\n\n    {\n      \"compilerOptions\": {\n        ...,\n        \"experimentalDecorators\": true\n      }\n    }\n\n## Installation\n\nInstall the module using npm:\n\n    npm install ts-method-cache --save\n\n## Examples\n\n### Simple usage:\n\n    import {MemoryCache} from \"ts-method-cache\";\n\n    export class HttpServiceWithCache {\n\n        @MemoryCache()\n        public getBar(foo: string): Promise\u003cstring\u003e {\n           return Promise.resolve(stuff + 'bar');\n        }\n\n    }\n\n\u003e No changes are needed inside your code to cache the returned value. Only add the decorator to your method, and the return\n\u003e value is cached\n\n## Limitations\n\nIt's not possible to store complex objects using `StorageCache` or `SessionCache`, like it is using `MemoryCache`. If\nthe object stored has methods or any other fancy stuff, this will most likely not work.\n\nThe only complex return types possible for cache based on Storage is a `Promise`.\n\n## API\n\n### `CacheType`\n\nEnum representing the different Cache Types:\n\n    CacheType.Memory\n    CacheType.Session\n    CacheType.Storage\n\n### `CacheReturnType`\n\nEnum representing the different Cache Return Types (Only used in Storage cache, not Memory cache):\n\n    CacheType.Static\n    CacheType.Promise\n\n### `CacheOptions`\n\nInterface object which you can use to adjust the behaviour of the cache decorator. All decorators support the following\noptions:\n\n    key?: string;\n\nThe key on which this method cache is stored under. Instead of a `CacheOptions` object, you can also just send a string\nas parameter in a decorator, and this will be set as the key. You can't adjust the ttl and returnType then. So this is\nprobably only advised for `@MemoryCache`\n\n    ttl?: string|number|Date\n\nTime to live. This can be a string, a number or Date object.\nThe string has to be a parsable Date string. The resulting Date is the end date as to how long the cache should live.\nThe Date object is the end date as to how long the cache should live.\nThe number is in seconds, and indicates how many seconds the cache is allowed to live its life\n\n    returnType?: CacheReturnType\n\nThe `returnType` only has effect on the `@SessionCache` and `@StorageCache` decorators. Because it is impossible to save\nthe entire `Promise` object inside a Storage object you should tell the decorator your method is returning a `Promise`\nby setting this to `CacheReturnType.Promise`.\n\n    cacheUntilRejected?: boolean\n\nWhen caching a method returning a Promise, this option will clear the relevant cache when the Promise is\nrejected. If the Promise resolves normally, the cache persists.\n\n### `MethodCacheService`\n\nPretty self explanatory method names:\n\n    clearAllCache(): void;\n    clearContainer(container: string): void;\n    clearKeyCache(type: CacheType, key: string): void;\n    clearMemoryContainer(container: string): void;\n    clearMemoryCache(): void;\n    clearMemoryKeyCache(key: string): void;\n    clearStorageContainer(container: string): void;\n    clearStorageCache(): void;\n    clearStorageKeyCache(key: string): void;\n    clearSessionContainer(container: string): void;\n    clearSessionCache(): void;\n    clearSessionKeyCache(key: string): void;\n\n### `@MemoryCache(options?: CacheOptions|string)`\n\nThis will cache the result of the method for the duration of the application. Refreshing the browser\nor restarting the application will clear the cache. This is the easiest form of caching, and there are no\nrestrictions. Which means you can return any object you would like (Promise/Observable/etc...)\n\nImport the `MemoryCache` method decorator from \"ts-method-cache\" and place it in front or above the method from which you\nwould like the return result to be cached. Caching is based on the passed parameters to the method itself and an optional\nkey string you can set as a parameter in the decorator: `@MethodCache(key)`. If the key is omitted, a GUID is generated.\nWhen you don't use a key, be sure to use a `CacheContainer`, because that will be the only way to manage the cache\ncreated on the method.\n\n_Simple usage:_\n\n    import {MemoryCache} from \"ts-method-cache\";\n\n    export class HttpServiceWithCache {\n\n        @MemoryCache()\n        public getStuff(stuff: string): Promise\u003cstring\u003e {\n           console.log(\"calling stuff: \" + stuff);\n           return Promise.resolve(\"returning stuff: \" + stuff);\n        }\n\n    }\n\n    const service: HttpServiceWithCache = new HttpServiceWithCache();\n\n    service.getStuff(\"books\").then(console.log);\n    service.getStuff(\"books\").then(console.log);\n    service.getStuff(\"cds\").then(console.log);\n    service.getStuff(\"cds\").then(console.log);\n\nThis will result in the following output:\n\n    /** @output\n    *  calling stuff: books\n    *  calling stuff: cds\n    *  returning stuff: books\n    *  returning stuff: books\n    *  returning stuff: cds\n    *  returning stuff: cds\n    */\n\nAs you can see the actual method is only called twice, while returning four times. It's magic!\n\n### `@CacheContainer(options: CacheOptions|string)`\n\nA `CacheContainer` is a class decorator which acts as a container for the method decorators placed on its methods. It\nhas a mandatory input which can be a key, or a `CacheOptions` object. If you define a `ttl` and/or a `returnType`, then\nthese values will be used as default values for the method decorators.\n\n### `@MemoryCache` usage with `@CacheContainer`, `CacheOptions` and the `MethodCacheService`:\n\n    @CacheContainer({key: 'TestContainer', ttl: 1})\n    export class HttpServiceWithCacheContainer {\n\n        @MemoryCache({key: 'GetStuff', ttl: 5})\n        public getStuff(stuff: string): Promise\u003cstring\u003e {\n            console.log(\"calling stuff: \" + stuff);\n            return Promise.resolve(\"returning: \" + stuff);\n        }\n\n        @MemoryCache()\n        public getOtherStuff(otherStuff: string): Promise\u003cstring\u003e {\n            console.log(\"calling otherStuff: \" + otherStuff);\n            return Promise.resolve(\"returning otherStuff: \" + otherStuff);\n        }\n\n    }\n\n    const service: HttpServiceWithCacheContainer = new HttpServiceWithCacheContainer();\n    const cacheService: MethodCacheService = new MethodCacheService();\n\n    service.getStuff(\"books\").then(console.log);\n    service.getOtherStuff(\"cds\").then(console.log);\n\n    setTimeout(() =\u003e {\n        service.getStuff(\"books\").then(console.log);\n        service.getOtherStuff(\"cds\").then(console.log);\n        cacheService.clearMemoryContainer('TestContainer');\n        service.getStuff(\"books\").then(console.log);\n        service.getOtherStuff(\"cds\").then(console.log);\n    }, 3000);\n\nThis will result in the following output:\n\n    /** @output\n    *   calling stuff: books\n    *   calling otherStuff: cds\n    *   returning: books\n    *   returning otherStuff: cds\n    *   calling otherStuff: cds\n    *   calling stuff: books\n    *   calling otherStuff: cds\n    *   returning: books\n    *   returning otherStuff: cds\n    *   returning: books\n    *   returning otherStuff: cds\n    */\n\nThis output is a bit harder to follow, but what happens is that by using a `ttl` inside the cache container, any method\ndecorator that does not have a ttl will inherit this ttl. (Same goes for `returnType` in the Storage decorators). This\nresults in calling the actual `otherStuff` method 3 times, because it expires after 1 second, and the `stuff` method\nonly twice, because this cache expires after 5 seconds.\n\nThe `clearMemoryContainer` clears all the cache present in the `CacheContainer`.\n\n### `@SessionCache(options: CacheOptions | string)`\n\nThis uses the browser's native `SessionStorage`. Therefor it is limited to the browser environment only. And with it comes\nthe limitations of storage. You can only store static objects or Promises using this decorator. To store a promise, set\nthe `returnType` property of the `StorageCacheOptions` to `CacheReturnType.Promise`. The return type defaults to `Static`.\n\nYou can also set the `returnType` as part of a `CacheContainer`. A method decorator will inherit this `returnType`.\n\nThe rest is the same as `@MethodCache`\n\n### `@StorageCache(options: CacheOptions | string)`\n\nThe same as `@SessionCache`, but instead of the browser's native `SessionStorage` it uses the `LocalStorage` of the\nbrowser. This can only be used inside the browser.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpierreduc%2Fts-method-cache","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpierreduc%2Fts-method-cache","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpierreduc%2Fts-method-cache/lists"}