{"id":22428305,"url":"https://github.com/momsfriendlydevco/generic-cache","last_synced_at":"2025-08-01T10:32:39.189Z","repository":{"id":78689326,"uuid":"107121799","full_name":"MomsFriendlyDevCo/generic-cache","owner":"MomsFriendlyDevCo","description":"Generic caching module for NodeJS","archived":false,"fork":false,"pushed_at":"2024-12-01T23:33:09.000Z","size":868,"stargazers_count":0,"open_issues_count":1,"forks_count":0,"subscribers_count":7,"default_branch":"master","last_synced_at":"2024-12-04T13:17:17.911Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","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/MomsFriendlyDevCo.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-10-16T12:04:24.000Z","updated_at":"2024-12-01T23:33:13.000Z","dependencies_parsed_at":"2024-11-27T06:34:23.545Z","dependency_job_id":null,"html_url":"https://github.com/MomsFriendlyDevCo/generic-cache","commit_stats":{"total_commits":94,"total_committers":2,"mean_commits":47.0,"dds":0.06382978723404253,"last_synced_commit":"a40d40d7e4f4702fcafba7ae6c9eacc25b9534c2"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MomsFriendlyDevCo%2Fgeneric-cache","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MomsFriendlyDevCo%2Fgeneric-cache/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MomsFriendlyDevCo%2Fgeneric-cache/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MomsFriendlyDevCo%2Fgeneric-cache/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MomsFriendlyDevCo","download_url":"https://codeload.github.com/MomsFriendlyDevCo/generic-cache/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":228363964,"owners_count":17908319,"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":[],"created_at":"2024-12-05T20:14:22.446Z","updated_at":"2024-12-05T20:14:22.970Z","avatar_url":"https://github.com/MomsFriendlyDevCo.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"@momsfriendlydevco/cache\n========================\nGeneric caching component.\n\nThis module is a low-level caching component designed to store, retrieve, expire and cleanup a simple key-value storage.\n\nFeatures:\n\n* Fully ES6 + promise compliant\n* Isomorphic back-end (Node) + front-end (Browser) support - just import and use\n* Module support for most main caching systems\n* Expiry based storage for all setters / getters\n* Automatic cleaning\n* Function wrapping and memorization support (via `cache.worker()`)\n* File contents caching (via `cache.fromFile()`, Node only)\n\n```javascript\nimport Cache from '@momsfriendlydevco/cache';\n\nconst storage = new Cache({\n\tmodules: ['memcached', 'mongo', 'memory'], // What modules to try to load (in order of preference)\n\t// module: 'redis', // Or just specify one\n});\n\n\n// Setup the first available caching system\nawait storage.init();\n\n\n// Set something (key, val, [expiry])\nstorage.set('myKey', 'myValue', '1h').then(setVal =\u003e ...)\n\n// Get something (key, [fallback])\nstorage.get('myKey', 'fallbackValue').then(val =\u003e ...)\n\n// Forget something (key)\nstorage.unset('myKey').then(()=\u003e ...)\n\n// Clean up storage, only supported by some modules\nstorage.clean().then(()=\u003e ...)\n\n// Hash something, objects also supported\nstorage.hash(complexObject, val =\u003e ...)\n```\n\nAll methods return a promise.\n\n\nSupported Caching Drivers\n=========================\n\n| Driver       | Requires         | Maximum object size | Serializer | list() | has() | size() | clean() | lock*() |\n|--------------|------------------|---------------------|------------|--------|-------|--------|---------|---------|\n| filesystem   | Writable FS area | Infinite            | Yes        | Yes    | Yes   | Yes    |         |         |\n| memcached    | MemcacheD daemon | 1mb                 | Yes        |        |       |        |         |         |\n| memory       | Nothing          | Infinite            | Not needed | Yes    | Yes   | Yes    | Yes     |         |\n| mongodb      | MongoDB daemon   | 16mb                | Disabled   | Yes    | Yes   |        | Yes     |         |\n| redis        | Redis daemon     | 512mb               | Yes        | Yes    | Yes   | Yes    |         | Yes     |\n| supabase     | Supabase account | Infinite            | Disabled   | Yes    | Yes   |        | Yes     |         |\n| localstorage | Browser          | Infinite            | Yes        | Yes    | Yes   | Yes    | Yes     |         |\n\n\n**NOTES**:\n\n* By default MemcacheD caches 1mb slabs, see the documentation of the daemon to increase this\n* While memory storage is theoretically infinite Node has a memory limit of 1.4gb by default. See the node CLI for details on how to increase this\n* Some caching systems (notably MemcacheD) automatically clean entries\n* For most modules the storage values are encoded / decoded via [marshal](https://github.com/MomsFriendlyDevCo/marshal). This means that complex JS primitives such as Dates, Sets etc. can be stored without issue. This is disabled in the case of MongoDB by default but can be enabled if needed\n* When `has()` querying is not supported by the module a `get()` operation will be performed and the result mangled into a boolean instead, this ensures that all modules support `has()` at the expense of efficiency\n* The localstorage module is only only available on the browser release\n* The Supabase module by default requires a simple key=\u003ejsonb table setup with a created + expires column. The simplest definition of this would be `create table cache (id character varying not null, created_at timestamp with time zone null default now(), expires_at timestamp with time zone null, data jsonb null, constraint cache_pkey primary key (id))`\n\n\nAPI\n===\n\n\nCache([options]) (constructor)\n------------------------------\nCreate a new cache handler and populate its default options.\n\nNote that `cache.init()` needs to be called and needs to complete before this module is usable.\n\n\ncache.options(Object) or cache.options(key, val)\n------------------------------------------------\nSet lots of options in the cache handler all at once or set a single key (dotted or array notation are supported).\n\n\nValid options are:\n\n| Option                         | Type           | Default                                                                            | Description                                                                                 |\n|--------------------------------|----------------|------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------|\n| `init`                         | Boolean        | `true`                                                                             | Whether to automatically run cache.init() when constructing                                 |\n| `cleanInit`                    | Boolean        | `false`                                                                            | Run `clean()` in the background on each init                                                |\n| `cleanAuto`                    | Boolean        | `false`                                                                            | Run `autoClean()` automatically in the background on init                                   |\n| `cleanAutoInterval`            | String         | `\"1h\"`                                                                             | Timestring to use when rescheduling `autoClean()`                                           |\n| `keyMangle`                    | Function       | `key =\u003e key`                                                                       | How to rewrite the requested key before get / set / unset operations                        |\n| `modules`                      | String / Array | `['memory']` / `'memory'`                                                          | What module(s) to attempt to load                                                           |\n| `module`                       | String / Array | `['memory']` / `'memory'`                                                          | Alternate spelling of `modules`                                                             |\n| `serialize`                    | Function       | `marshal.serialize`                                                                | The serializing function to use when storing objects                                        |\n| `deserialize`                  | Function       | `marshal.deserialize`                                                              | The deserializing function to use when restoring objects                                    |\n| `filesystem`                   | Object         | See below                                                                          | Filesystem module specific settings                                                         |\n| `filesystem.fallbackDate`      | Date           | `2500-01-01`                                                                       | Fallback date to use as the filesystem expiry time                                          |\n| `filesystem.memoryFuzz`        | Number         | `200`                                                                              | How many Milliseconds bias to use when comparing the file ctime to the memory creation date |\n| `filesystem.moveFailTries`     | Number         | `30`                                                                               | Maximum number of tries before giving up moving swap files over live files                  |\n| `filesystem.moveFailInterval`  | Number         | `100`                                                                              | Delay between retries                                                                       |\n| `filesystem.utimeFailTries`    | Number         | `30`                                                                               | Maximum number of tries before giving up setting the utime on the swap file                 |\n| `filesystem.utimeFailInterval` | Number         | `100`                                                                              | Delay between retries                                                                       |\n| `filesystem.path`              | Function       | os.tempdir + key + '.cache.json'                                                   | How to calculate the file path to save. Defaults to the OS temp dir                         |\n| `filesystem.pathSwap`          | Function       | \" + \" + '.cache.swap.json'                                                         | How to calculate the swap path to save. Defaults to the OS temp dir                         |\n| `memcached`                    | Object         | See below                                                                          | MemcacheD module specific settings                                                          |\n| `memcached.server`             | String         | `'127.0.0.1:11211'`                                                                | The MemcacheD server address to use                                                         |\n| `memcached.lifetime`           | Number         | `1000*60` (1h)                                                                     | The default expiry time, unless otherwise specified                                         |\n| `memcached.options`            | Object         | `{retries:1,timeout:250}`                                                          | Additional options passed to the MemcacheD client                                           |\n| `mongodb`                      | Object         | See below                                                                          | MongoDB module specific options                                                             |\n| `mongodb.uri`                  | String         | `'mongodb://localhost/mfdc-cache'`                                                 | The MongoDB URI to connect to                                                               |\n| `mongodb.collection`           | String         | `mfdcCaches`                                                                       | The collection to store cache information within                                            |\n| `mongodb.options`              | Object         | See code                                                                           | Additional Mongo options to use when connecting                                             |\n| `redis`                        | Object         | [See Redis module settings](https://www.npmjs.com/package/redis#rediscreateclient) | Settings passed to Redis                                                                    |\n| `supabase`                     | Object         |                                                                                    | See below                                                                                   | Supabase config |\n| `supabase.uri`                 | String         | `null`                                                                             | The Supabase URL to communicate with                                                        |\n| `supabase.apikey`              | String         | `null`                                                                             | The Supabase API key to use                                                                 |\n| `supabase.options`             | Object         | `{}`                                                                               | Additional options to pass during the connection                                            |\n| `supabase.table`               | String         | `'cache'`                                                                          | The caching table to use                                                                    |\n| `supabase.colId`               | String         | `'id'`                                                                             | The column ID to use (should be an indexed key)                                             |\n| `supabase.colData`             | String         | `'data'` The JSONB column used to stash data                                       |\n\n\n**NOTES**:\n\n* All modules expose their own `serialize` / `deserialize` properties which defaults to the main properties by default. These are omitted from the above table for brevity\n* The default setup for the serialize property assumes no circular references, override this if you really do need to store them - but at a major performance hit\n* The MongoDB module does *not* serialize or deserialize by default in order to use its own storage format, set the `serialize` / `deserialize` properties to the main cache object to enable this behaviour\n* `filesystem.moveFailTries` is necessary because on some systems writing the temporary swap file, setting its expiry then trying to move it over the live file sometimes fails. TO work around this we wait for the filesystem to flush the maximum number of times with a delay in between.\n\n\n\ncache.option()\n--------------\nAlias of `cache.options()`.\n\n\ncache.init()\n------------\nInitialize the cache handler and attempt to load the modules in preference order.\nThis function is automatically executed in the constructor if `cache.settings.init` is truthy.\nThis function returns a promise.\n\n\ncache.autoClean(newInterval)\n----------------------------\nSetup a time to clean out all expired cache items.\nIf no interval is provided the option `autoCleanInterval` is used.\nIf the interval is falsy the timer is disabled.\n\n\ncache.set(Object, [expiry]) or cache.set(key, value, [expiry])\n--------------------------------------------------------------------------------------\nSet a collection of keys or a single key with the optional expiry.\nThe expiry value can be a date, millisecond offset, moment object or any valid [timestring](https://www.npmjs.com/package/timestring) string.\nThis function returns a promise.\n\n\ncache.get(key|keys)\n-------------------------------------------\nFetch a single / multiple values. If the value does not exist the fallback value will be provided.\nIf called with an array of keys the result is an object with a key/value combination.\nThis function returns a promise.\n\n\ncache.unset(key|keys)\n---------------------------------\nRelease a single or array of keys.\nThis function returns a promise.\n\n\ncache.has(key)\n--------------------------\nReturn whether we have the given key but not actually fetch it.\nNOTE: If the individual module does not implement this a simple `get()` will be performed and the return mangled into a boolean. See the compatibility tables at the top of this article to see if 'has' is supported.\nThis function returns a promise.\n\n\ncache.size(key)\n---------------------------\nReturn whether the approximate size in bytes of a cache object.\nThis function returns a promise.\n\n\ncache.list()\n------------\nAttempt to return a list of known cache contents.\nThis function returns a promise.\n\nEach item will have at minimum a `id` and `created` value. All other values (e.g. `expiry`) depend on the cache driver being used.\n\n\n\ncache.clean()\n-------------\nAttempt to clean up any left over or expired cache entries.\nThis is only supported by some modules.\nThis function returns a promise.\n\n\ncache.destroy()\n---------------\nPolitely close all driver resource handles before shutting down.\nThis function waits for all set operations to complete before resolving.\nThis function returns a promise.\n\n\ncache.lockAquire(key, expiry)\n-----------------------------\nRequest the creation of a unique lock specified by the hashed version of the key (with an optional expiry).\nThis function returns a promise with a boolean indicating if the lock aquire was successful.\n\n\ncache.lockRelease(key)\n----------------------\nRelease an aquired lock.\nThis function returns a promise.\n\n\ncache.lockExists(key)\n---------------------\nQuery the status of a lock.\nThis function returns a promise with a boolean indicating if the lock exists.\n\n\ncache.lockSpin(key, options)\n----------------------------\nReturns a Promise which repeatedly checks if a key exists a given number of times (with configurable retires / backoff).\nIf the key is eventually available, it is created otherwise this function throws.\n\nOptions are:\n\n| Option        | Type       | Default | Description                                                                                                                                                                         |\n|---------------|------------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `expiry`      | TimeString |         | Optional expiry for the lock                                                                                                                                                        |\n| `retries`     | `Number`   | `5`     | Maximum number of retries to attempt                                                                                                                                                |\n| `delay`       | `Number`   | `250`   | Time in milliseconds to wait for a lock using the default backoff system                                                                                                            |\n| `create`      | `Boolean`  | `true`  | If a lock can be allocated, auto allocate it before resuming                                                                                                                        |\n| `backoff`     | `Function` |         | Function to calculate timing backoff, should return the delay to use. Called as `(attempt, max, settings)`. Defaults to simple linear backoff using `delay` + some millisecond fuzz |\n| `onLocked`    | `Function` |         | Async function to call each time a lock is detected. Called as `(attempt, max, settings)`                                                                                           |\n| `onCreate`    | `Function` |         | Async function to call if allocating a lock is successful. Called as `(attempt, max, settings)`                                                                                     |\n| `onExhausted` | `Function` |         | Async function to call if allocating a lock failed after multiple retries. Called as `(attempt, max, settings)`. Should throw                                                       |\n\n\ncache.fromFile(key, path, expiry)\n---------------------------------\nHelper function to read a local file into the cache\nOnly available within NodeJS.\nSince disk files are (kind of) immutable this function works as both a getter (fetch file contents) and a setter (populate into cache)\nThe file's stats are taken into account when reading so that changed files (filesize + date) get hydrated if needed\nThis function returns a promise with the cached files contents.\n\n\ncache.middleware(expiry, options)\n---------------------------------\nExpressJS / Connect compatible middleware layer to provide caching middleware.\nReturns an ExpressJS / Connect middleware function.\nOnly available within NodeJS.\n\nExpiry is optional but if provided as a string is assumed to populate `options.expiry`.\n\nOptions are:\n\n| Option        | Type                                 | Default      | Description                                                                                                                                                                  |\n|---------------|--------------------------------------|--------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `expiry`      | `String`                             | `'5m'`       | The expiry of the cache item\n| `key`         | `String`, `Object`, `Function\u003cString|*\u003e` |          |Overriding name (or hashable object) to use as the caching key, if omitted the `hash` method is used to calculate the key instead. If an async function it is run as `(req)` |\n| `keyMangle`   | `Function\u003cString\u003e`                   |              | How to mangle the now computed key string into the key that is actually stored within the cache. Defaults to prefixing with `'middleware/'`                                  |\n| `hash`        | `Function\u003cString|*\u003e`                 |              | Fallback method if `options.key` is unspecified to hash the incomming request. Defaults to hashing the method, path, query and body                                          |\n| `eTag`        | `Boolean`                            | `true`       | Whether to generate + obey the eTag http spec. Clients providing a valid eTag will get a 304 response if that tag is still valid                                             |\n| `hashETag`    | `Function\u003cString\u003e`                   | SHA1 w/Bas64 | Async function to generate the client visible eTag from the computed key (post keyMangle)                                                                                    |\n| `context`     | `Object`                             | `Cache`      | Function context used for `key`, `hash` \u0026 `cacheFilter` functions if called. Defaults to this cache instance                                                                 |\n| `cacheFilter` | `Function`                           | `()=\u003etrue`   | Async function used to determine whether the output value should be cached when generated. Called as `(req, res, content)` and expected to eventually return a boolean       |\n\n\ncache.semaphore(options)\n------------------------\nExpressJS / Connect compatible middleware layer to provide restrict incomming endpoints to use a single worker thread at a time.\nIf the same endpoint is hit while the worker is still active, the subsequent hits are queued and forced to accept the first worker resolution.\nThis middleware is thread-safe, using both local state + cross processor caching to manage state. It is also designed to work with `cache.middleware()` if the cached state needs to be preserved longer than the worker functioning.\n\nReturns an ExpressJS / Connect middleware function.\nOnly available within NodeJS.\n\nOptions are:\n\n| Option             | Type                             | Default | Description                                                                                                                                                                  |\n|--------------------|----------------------------------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `useLocal`         | `Boolean`                        | `true`  | Try to use local state promise chains first, this will capture cases only directed as a single process server                                                                |\n| `key`              | `String` / `Object` / `Function` |         | Overriding name (or hashable object) to use as the caching key, if omitted the `hash` method is used to calculate the key instead. If an async function it is run as `(req)` |\n| `keyMangleLock`    | `Function`                       |         | How to mangle the now computed key string into the lock that is actually stored within the cache                                                                             |\n| `keyMangleSession` | `Function`                       |         | How to mangle the now computed key string into the session result that is actually stored within the cache                                                                   |\n| `resultExpiry`     | `String`                         | `\"5m\"`  | How long to keep the resulting value before cleaning it up                                                                                                                   |\n| `hash`             | `Function`                       |         | Fallback method if `options.key` is unspecified to hash the incomming request. Defaults to hashing the method, path, query and body                                          |\n| `retries`          | `Number`                         | `2400`  | Maximum number of retries to attempt when locking, set to zero to disable, this multiplied by the delay should exceed the maximum execution time of the worker function      |\n| `delay`            | `Number`                         | `250`   | Time in milliseconds to wait for a lock using the default backoff system                                                                                                     |\n| `expiry`           | `String`                         | `'10m'` | The expiry of the lock, this should exceed the maximum execution time of the worker function                                                                                 |\n\n\ncache.worker(options, worker)\n-----------------------------\nSimple wrapper middleware function which either returns the cached ID or runs a worker to calculate + cache a new one.\nNOTE: Since Promise execute immediately the worker must be a promise factory\n\nOptions can either be a string (assumed as `options.id`) or an object made up of:\n\n| Option         | Type                  | Default     | Description                                                                                                                                                                                                                                                                                       |\n|----------------|-----------------------|-------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `id`           | `String`              |             | The ID of the cache to use                                                                                                                                                                                                                                                                        |\n| `enabled`      | `Boolean`             | `true`      | Whether to use the cache at all, set to false to debug the function worker each time                                                                                                                                                                                                              |\n| `expiry`       | `String`              | `\"1h\"`      | Any timesting valid entry to determine the maximum cache time                                                                                                                                                                                                                                     |\n| `rejectAs`     | `Boolean`             | `undefined` | Cache throwing promises as this value rather than repeating them each hit                                                                                                                                                                                                                         |\n| `retry`        | `Number`              | `0`         | If a promise rejects retry it this many times before giving up                                                                                                                                                                                                                                    |\n| `retryDelay`   | `Number` / `Function` | `100`       | Delay between promise retries, if a function is called as `(attempt, settings)` and expected to return the delay amount                                                                                                                                                                           |\n| `onCached`     | `Function`            |             | Sync function to called as `(settings, value)` when using a valid cached value instead of hydrating the worker, if any value except `undef` is returned it is used as the returned value                                                                                                          |\n| `onRetry`      | `Function`            |             | Sync function to call as `(error, attempt)` when a retryable operation fails, if any non-undefined is returned the retry cycle is aborted and the value used as the promise resolve value, if the function throws the entire promise retry cycle is exited with the thrown error as the rejection |\n| `invalidStore` | `*`                   |             | Value use to detect the absence of a value in the cache (so we can detect null/undefined values even though they are falsy)                                                                                                                                                                       |\n\n\nDebugging\n=========\nThis module uses the [debug NPM module](https://github.com/visionmedia/debug) for debugging. To enable set the environment variable to `DEBUG=cache`.\n\nFor example:\n\n```\nDEBUG=cache node myFile.js\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmomsfriendlydevco%2Fgeneric-cache","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmomsfriendlydevco%2Fgeneric-cache","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmomsfriendlydevco%2Fgeneric-cache/lists"}