@jasonsoft/nestjs-redis
v1.0.2
Published
Redis module for Nest framework (node.js)
Downloads
114
Maintainers
Readme
nestjs-redis
Redis(ioredis) module for Nest framework (node.js) 🚀
Installation
$ npm i --save @jasonsoft/nestjs-redis ioredis
Usage
Import RedisModule
:
@Module({
imports: [
RedisModule.forRoot({
isGlobal: true,
url: 'redis://username:password@localhost:6379',
}),
],
providers: [...],
})
export class AppModule {}
@Module({
imports: [
RedisModule.forRoot({
port: 6379, // Redis port
host: 'localhost', // Redis host
username: 'default', // needs Redis >= 6
password: 'password',
db: 0, // Defaults to 0
}),
],
providers: [...],
})
export class AppModule {}
Inject RedisCacheHelper
:
@Injectable()
export class AppService {
constructor(private readonly redisCacheHelper: RedisCacheHelper) {}
}
Async options
Quite often you might want to asynchronously pass your module options instead of passing them beforehand. In such case, use forRootAsync()
method.
RedisModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
url: configService.get('REDIS_URL'),
}),
inject: [ConfigService],
}),
Example
import { RedisCacheHelper } from '@jasonsoft/nestjs-redis';
import { Injectable } from '@nestjs/common';
export interface User {
id: number;
name: string;
age: number;
}
export const USERS: User[] = [
{
id: 1,
name: 'Jason Song',
age: 18,
},
{
id: 2,
name: '成长的小猪',
age: 30,
},
];
@Injectable()
export class AppService {
constructor(private readonly redisCacheHelper: RedisCacheHelper) {}
async getUser(id: number): Promise<User> {
const cacheKey = `user:${id}`;
let user = await this.redisCacheHelper.getAsObj<User>(cacheKey);
if (!user) {
user = USERS.find((user) => user.id === id);
if (user) {
await this.redisCacheHelper.set(cacheKey, user);
}
}
return user;
}
async commonOperation() {
/** string type */
await this.redisCacheHelper.set('string:type', 'test', 60);
const stringValue = await this.redisCacheHelper.getAsStr('string:type');
/** number type */
await this.redisCacheHelper.set('number:type', 1, '30m');
const numberValue = await this.redisCacheHelper.getAsNum('number:type');
/** boolean type */
await this.redisCacheHelper.set('boolean:type', true, '8h');
const booleanValue = await this.redisCacheHelper.getAsBool('boolean:type');
/** object:type */
const user = USERS.find((user) => user.name === 'Jason Song');
await this.redisCacheHelper.set('object:type', user, '7d');
const objectValue = await this.redisCacheHelper.getAsObj<User>(
'object:type',
);
}
}