Skip to content

Commit

Permalink
Website - updating remaining caching docs with cacheable using keyv (#…
Browse files Browse the repository at this point in the history
…1210)

* website - updating remaining caching docs with Cacheable using Keyv

* updating node and nestjs
  • Loading branch information
jaredwray authored Nov 14, 2024
1 parent 8ee9292 commit b698bde
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 66 deletions.
23 changes: 14 additions & 9 deletions packages/website/site/docs/caching/caching-koa.md
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
```
28 changes: 15 additions & 13 deletions packages/website/site/docs/caching/caching-nestjs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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 {}
```
Expand All @@ -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<T>(key: string): Promise<T> {
return await this.keyv.get<T>(key);
return await this.cache.get<T>(key);
}

async set<T>(key: string, value: T, ttl?: number): Promise<void> {
await this.keyv.set<T>(key, value, ttl);
async set<T>(key: string, value: T, ttl?: number | string): Promise<void> {
await this.cache.set<T>(key, value, ttl);
}

async delete(key: string): Promise<void> {
await this.keyv.delete(key);
await this.cache.delete(key);
}
}
```
Expand Down Expand Up @@ -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 {
Expand Down
51 changes: 7 additions & 44 deletions packages/website/site/docs/caching/caching-node.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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() {
Expand All @@ -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.

0 comments on commit b698bde

Please sign in to comment.