In NestJS framework, I have an array of object, each object contains an instance of my car class, this class have a lot of public and private property and some method. Since my project doesn’t have any database except Redis and sometimes restart unexpectedly; I want to store this array of object into Redis DB every one minute.
My main TypeScript file is like this:
class car {
public name ;
private model;
constructor(car_name){
this.name = car_name;
}
start() {
console.log(this.name + ' start the engine');
}
}
let myBMW = new car('bmw');
let myNISSAN = new car('nissan');
let arr_of_obj = [
{
name : "bmw",
type : "racing",
mymethod : myBMW
},
{
name : "nissan",
type : "sedan",
mymethod : myNISSAN
}
];
and my Redis service is:
import { Inject, Injectable } from '@nestjs/common';
import Redis from 'ioredis';
@Injectable()
export class RedisDbService {
constructor(@Inject('REDIS_CLIENT') private readonly redisClient: Redis) {}
async set(key: string, value: any, ex: number) {
return await this.redisClient.set(key, JSON.stringify(value), 'EX', ex);
}
async get(key: string) {
const data = await this.redisClient.get(key);
if(data == null){
return [];
}
return JSON.parse(data);
}
async deletekey(key: string) {
return this.redisClient.del(key);
}
}
So, when I use this line of codes I get error start() is not a function:
this.redisService.set('car_in_redis', myBMW , 300);
let new_car = await this.redisService.get('car_in_redis');
new_car.start();
I know the JSON.stringify()
and JSON.parse()
is the reason but how to store an instance completely inside Redis?
UY Scuti is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1