diff --git a/packages/website/site/docs/caching/caching-koa.md b/packages/website/site/docs/caching/caching-koa.md index 8da0f98b7..9d69292db 100644 --- a/packages/website/site/docs/caching/caching-koa.md +++ b/packages/website/site/docs/caching/caching-koa.md @@ -12,28 +12,33 @@ Koa is a web framework from the team behind Express that offers a smaller, more ## What is a Cache? A cache is a short-term, high-speed data storage layer that stores a subset of data, enabling it to be retrieved faster than accessing it from its primary storage location. Caching allows you to reuse previously retrieved data efficiently. -## Caching Support in Keyv -Caching will work in memory by default. However, users can also install a Keyv storage adapter that is initialized with a connection string or any other storage that implements the Map API. +## Caching Support in Keyv via Cacheable + +We can use Keyv to implement caching using [Cacheable](https://npmjs.org/package/cacheable) which is a high performance layer 1 / layer 2 caching framework built on Keyv. It supports multiple storage backends and provides a simple, consistent API for caching. ### Example - Add Cache Support Using Koa ```js -import keyv from 'keyv'; +import Koa from 'koa'; +import { Cacheable } from 'cacheable'; +import KeyvRedis from '@keyv/redis'; + +// by default layer 1 cache is in-memory. If you want to add a layer 2 cache, you can use KeyvRedis +const secondary = new KeyvRedis('redis://user:pass@localhost:6379'); +const cache = new Cacheable({ secondary, ttl: '4h' }); // default time to live set to 4 hours -// ... -const cache = new Keyv(); -const cacheTTL = 1000 * 60 * 60 * 24; // 24 hours +const app = new Koa(); app.use(async ctx => { // this response is already cashed if `true` is returned, // so this middleware will automatically serve this response from cache - if (await keyv.get(ctx.url)) { - return keyv.get(ctx.url); + if (await cache.get(ctx.url)) { + return cache.get(ctx.url); } // set the response body here ctx.body = 'hello world!'; // cache the response - await keyv.set(ctx.url, ctx.body. cacheTTL); + await cache.set(ctx.url, ctx.body. cacheTTL); }); ``` \ No newline at end of file diff --git a/packages/website/site/docs/caching/caching-nestjs.md b/packages/website/site/docs/caching/caching-nestjs.md index 2dafc9a27..3b8ebdefc 100644 --- a/packages/website/site/docs/caching/caching-nestjs.md +++ b/packages/website/site/docs/caching/caching-nestjs.md @@ -20,7 +20,7 @@ $ cd nestjs-keyv-cache To begin, install Keyv and a storage adapter of your choice. In this example, we'll use SQLite: ```bash -$ npm install keyv keyv-sqlite +$ npm install cacheable @keyv/redis --save ``` ## 3. Integrating Keyv with NestJS @@ -33,17 +33,20 @@ Then, update the cache.module.ts file to import and configure Keyv: ```javascript import { Module } from '@nestjs/common'; -import { Keyv } from 'keyv'; -import KeyvSqlite from 'keyv-sqlite'; +import { Cacheable } from 'cacheable'; +import KeyvRedis from '@keyv/redis'; @Module({ providers: [ { - provide: 'KEYV_INSTANCE', - useFactory: () => new Keyv({ store: new KeyvSqlite('sqlite://cache.sqlite') }), + provide: 'CACHE_INSTANCE', + useFactory: () => { + const secondary = new KeyvRedis('redis://user:pass@localhost:6379'); + return new Cacheable({ secondary, ttl: '4h' }); + }, }, ], - exports: ['KEYV_INSTANCE'], + exports: ['CACHE_INSTANCE'], }) export class CacheModule {} ``` @@ -69,22 +72,21 @@ Update the cache.service.ts file with caching methods: ```javascript import { Inject, Injectable } from '@nestjs/common'; -import { Keyv } from 'keyv'; @Injectable() export class CacheService { - constructor(@Inject('KEYV_INSTANCE') private readonly keyv: Keyv) {} + constructor(@Inject('CACHE_INSTANCE') private readonly cache: Cacheable) {} async get(key: string): Promise { - return await this.keyv.get(key); + return await this.cache.get(key); } - async set(key: string, value: T, ttl?: number): Promise { - await this.keyv.set(key, value, ttl); + async set(key: string, value: T, ttl?: number | string): Promise { + await this.cache.set(key, value, ttl); } async delete(key: string): Promise { - await this.keyv.delete(key); + await this.cache.delete(key); } } ``` @@ -113,7 +115,7 @@ export class SampleController { if (!data) { // Simulate fetching data from an external API data = 'Sample data from external API'; - await this.cacheService.set(cacheKey, data, 60 * 1000); // Cache for 1 minute + await this.cacheService.set(cacheKey, data, '1m'); // Cache for 1 minute } return { diff --git a/packages/website/site/docs/caching/caching-node.md b/packages/website/site/docs/caching/caching-node.md index b808cdc09..e8a2e0d31 100644 --- a/packages/website/site/docs/caching/caching-node.md +++ b/packages/website/site/docs/caching/caching-node.md @@ -17,10 +17,10 @@ npm init -y The npm init -y command will create a new package.json file in your project directory with default settings. ## 2. Installing Keyv and its Dependencies -In this step, you'll install Keyv and a Keyv storage adapter for your project. For this example, we'll use SQLite as the storage adapter. +In this step, you'll install Keyv and a Keyv storage adapter for your project. For this example, we'll use Redis as the storage backend. ```bash -npm install keyv @keyv/sqlite +npm install cacheable @keyv/redis --save ``` Keyv supports a variety of storage adapters like Redis, MongoDB, PostgreSQL, etc. Feel free to choose the one that best fits your project requirements. @@ -30,47 +30,12 @@ In this step, we'll create a simple caching service using Keyv. Create a new file named cacheService.js in your project directory and add the following code to that file. ```javascript -const Keyv = require('keyv'); -const keyv = new Keyv('sqlite://path/to/database.sqlite'); +import { Cacheable } from 'cacheable'; +import KeyvRedis from '@keyv/redis'; -class CacheService { - async get(key) { - const value = await keyv.get(key); - if (value) { - console.log('Cache hit'); - } else { - console.log('Cache miss'); - } - return value; - } - - async set(key, value, ttlInMilliseconds) { - await keyv.set(key, value, ttlInMilliseconds); - } - - async delete(key) { - await keyv.delete(key); - } -} - -module.exports = CacheService; -``` - -In this code: - -We're importing the Keyv library and initializing it with an SQLite database. - -We're creating a CacheService class with get, set, and delete methods that wrap the corresponding methods of the Keyv instance. The get method includes console logs to indicate whether the requested value was found in the cache. - -The set method includes an optional ttlInMilliseconds parameter, which you can use to set a time-to-live (TTL) for the cached value. - -Now you have a reusable CacheService that you can use to add caching to your Node.js project. - -Here is how you could use the CacheService: - -```javascript -const CacheService = require('./cacheService'); -const cache = new CacheService(); +// Initialize Keyv with Redis as the storage backend +const secondary = new KeyvRedis('redis://user:pass@localhost:6379'); +const cache = new Cacheable({ secondary, ttl: '4h' }); // default time to live set to 4 hours // Usage async function fetchData() { @@ -83,5 +48,3 @@ async function fetchData() { return data; } ``` - -This is a basic example, and Keyv provides a lot of flexibility, so you can modify this service to better suit your project's needs.