{"id":18552458,"url":"https://github.com/andrejewski/n-level-cache","last_synced_at":"2025-04-09T22:31:55.093Z","repository":{"id":57307277,"uuid":"63334053","full_name":"andrejewski/n-level-cache","owner":"andrejewski","description":"Multi-level cache with any number of levels and gracefully fallback to the computed value","archived":false,"fork":false,"pushed_at":"2017-04-10T17:00:35.000Z","size":24,"stargazers_count":8,"open_issues_count":0,"forks_count":2,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-04-05T00:02:38.751Z","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":"isc","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/andrejewski.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}},"created_at":"2016-07-14T12:17:50.000Z","updated_at":"2020-01-22T13:54:34.000Z","dependencies_parsed_at":"2022-09-20T21:50:11.765Z","dependency_job_id":null,"html_url":"https://github.com/andrejewski/n-level-cache","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrejewski%2Fn-level-cache","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrejewski%2Fn-level-cache/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrejewski%2Fn-level-cache/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrejewski%2Fn-level-cache/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/andrejewski","download_url":"https://codeload.github.com/andrejewski/n-level-cache/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248123746,"owners_count":21051523,"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-11-06T21:14:16.306Z","updated_at":"2025-04-09T22:31:54.732Z","avatar_url":"https://github.com/andrejewski.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# n-level-cache\nMulti-level cache with any number of levels and gracefully fallback to the computed value.\n\n```sh\nnpm install n-level-cache\n```\n\n## Explanation\nSome systems have multiple layers of caching. On the server, these layers might be played by an in-memory data store (a hash map), any number of key-value data stores (Redis and Memcache), and finally a source of truth which is usually a database like Amazon's Dynamo or Postgres.\n\nThe goal of `n-level-cache` is to abstract away all the plumbing of multi-level caching by\n\n- Reading from each cache one at a time, fastest to slowest, trying to get a cached value\n- Computing the source of truth value if no cached value is found and writing it to all cache levels and finally returning the value\n- Handling failures at any cache level, allowing other cache levels to work properly\n- Rehydrating faster caches with values from slower caches\n- Providing a consistent interface for building your caches and handling per-cache errors\n\n## Examples\n\n```js\nconst NLevelCache = require('n-level-cache')\n\n// example: Redis (promisified)\nclass RedisCache {\n  constructor (redis) {\n    this.redis = redis\n  },\n  get (key, options) {\n    return this.redis.get(key)\n  },\n  set (key, value, options) {\n    if (options.ttl) {\n      return this.redis.setex(key, options.ttl, value)\n    }\n    return this.redis.set(key, value)\n  },\n  onGetError (error) {/* log this */}\n  onSetError (error) {/* log this */}\n}\n\nconst nLevelCache = new NLevelCache({\n  caches: [\n    new RedisCache(redisClientL1),\n    new RedisCache(redisClientL2)\n  ],\n  compute (key) {\n    // optional last resort: if the cached value\n    // is not found it will be computed, cached,\n    // and returned to the caller\n    return myDatabase.users.findById(key)\n  }\n})\n\nreturn nLevelCache.get(userId).then(value =\u003e {\n  // ...\n})\n```\n\n```js\n// example: Local/SessionStorage (in browser only)\nclass LocalCache {\n  constructor (storage) {\n    this.storage = storage\n  },\n  get (key, options) {\n    return Promise.resolve(JSON.parse(this.storage.getItem(key)))\n  },\n  set (key, value, options) {\n    this.storage.setItem(key, JSON.stringify(value))\n    return Promise.resolve()\n  }\n}\n\nconst browserCaches = [\n  new LocalCache(window.localStorage),\n  new LocalCache(window.sessionStorage)\n]\n\nconst nLevelCache = new NLevelCache({ caches: browserCaches })\n\nnLevelCache.get(myKey).then(value =\u003e {\n  console.log(value)\n  // ^ will print the value if it is found in localStorage or\n  // sessionStorage, otherwise value is null\n})\n```\n\n## Documentation\n\n### class NLevelCache(options)\n```js\nconst nLevelCache = new NLevelCache({\n  // default options shown\n  caches: [], // ordered by fastest to slowest\n              // see \"Cache interface\" below for details\n\n  compute (query, options) {\n    // computes the value if it is not found in any cache\n    // query and options are passed directly from set/get\n    // must return a promise\n    return Promise.resolve(void 0)\n  },\n\n  isValue (x) {\n    // checks a value returned from a cache\n    // if true, the cache returned a useful value\n    // why have this? sometimes null may be considered valid\n    return x !== null \u0026\u0026 x !== void 0\n  },\n\n  hydrate: true,  // if true, if a value is found in a higher cache\n                  // that value is set on all lower caches\n                  // so the next time those caches have the value\n\n  keyForQuery (query) {\n    // returns a key for a given query\n    // why have this? compute() take a query that can be complex\n    // but caches only need a key.\n    // For example: compute({model: 'user', id: 'chris'})\n    // But the key would be \"users:chris\" if configured here\n    // (Don't implement if your caches have different key schemes)\n    return query\n  }\n})\n```\n\n### NLevelCache.get(query Any, options Object) Promise\nResolves with a cached value if found, otherwise the computed value. Rejects only if the computed value rejects. Any `options` passed will be passed along to the implemented cache methods.\n\n### NLevelCache.set(query Any, options Object) Promise\nResolves with the computed value or rejects with the computed rejection. Writes the computed value to all caches as well. Any `options` passed will be passed along to the implemented cache methods.\n\n### Cache interface\nCaches passed to `n-level-cache` must fit the following interface. A cache does not have to be a class instance, it can be any object with these methods.\n\n```js\nclass Cache {\n  // required methods (must return a Promise):\n  get (key, options) { return Promise.resolve(value) }\n  set (key, value, options) { return Promise.resolve() }\n\n  // optional error handlers\n  onGetError (error) {}\n  onSetError (error) {}\n}\n```\n\n## Contributing\n\nContributions are incredibly welcome as long as they are standardly applicable and pass the tests (or break bad ones). Tests are done with AVA.\n\n```sh\n# running tests\nnpm run test\n```\n\nFollow me on [Twitter](https://twitter.com/compooter) for updates or just for the lolz and please check out my other [repositories](https://github.com/andrejewski) if I have earned it. I thank you for reading.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandrejewski%2Fn-level-cache","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fandrejewski%2Fn-level-cache","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandrejewski%2Fn-level-cache/lists"}