Skip to content

Commit

Permalink
updating node and nestjs
Browse files Browse the repository at this point in the history
  • Loading branch information
jaredwray committed Nov 14, 2024
1 parent 5fcb975 commit 623c286
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 57 deletions.
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 623c286

Please sign in to comment.