Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Implement caching in DriverService for optimized data retrieval #17

Merged
merged 2 commits into from
Jul 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion apps/driver/src/driver.controller.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Controller, Get } from '@nestjs/common';
import { DriverService } from './driver.service';
import { MessagePattern } from '@nestjs/microservices';
import { DriverDto } from '@app/shared/events/driver/driver.dto';
import { Driver } from './models/driver.entity';

@Controller('drivers')
Expand Down
5 changes: 5 additions & 0 deletions apps/driver/src/driver.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { DriverService } from './driver.service';
import * as dotenv from 'dotenv';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Driver } from './models/driver.entity';
import { CacheModule } from '@nestjs/cache-manager';


dotenv.config();
Expand All @@ -17,6 +18,10 @@ dotenv.config();
process.env.DATABASE_NAME,
process.env.DATABASE_TYPE as 'mongodb' | 'postgres'
),
CacheModule.register({
ttl: 60, // seconds
max: 100, // maximum number of items in cache
}),
],
controllers: [DriverController],
providers: [DriverService],
Expand Down
36 changes: 32 additions & 4 deletions apps/driver/src/driver.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { Injectable, Logger } from '@nestjs/common';
import { Inject, Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { DriverStatus } from './enums/driver.status';
import { Driver } from './models/driver.entity';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';



Expand All @@ -13,7 +15,9 @@ export class DriverService {

constructor(
@InjectRepository(Driver)
private readonly driverRepository: Repository<Driver>
private readonly driverRepository: Repository<Driver>,
@Inject(CACHE_MANAGER)
private readonly cacheManager: Cache,
) {}

async createDriver(userId: string): Promise<Driver> {
Expand All @@ -34,15 +38,38 @@ export class DriverService {
}

async findAllDrivers(): Promise<Driver[]> {
this.logger.log('Begin fetching all drivers');

const cacheKey = 'all-drivers';
const cachedDrivers = await this.cacheManager.get<Driver[]>(cacheKey);

if (cachedDrivers) {
this.logger.log('Drivers fetched from cache');
return cachedDrivers;
}

try {
return await this.driverRepository.find();
const drivers = await this.driverRepository.find();
await this.cacheManager.set(cacheKey, drivers, 600 ); // cache for 10 minutes
this.logger.log('Drivers fetched from database and cached');
return drivers;
} catch (error) {
this.logger.error(`Error while fetching drivers from database: ${error.message}`);
throw error;
}
}

async findAllSortedByStatus(): Promise<Driver[]> {
this.logger.log('Begin fetching and sorting all drivers by status');

const cacheKey = 'all-drivers-sorted-by-status';
const cachedSortedDrivers = await this.cacheManager.get<Driver[]>(cacheKey);

if (cachedSortedDrivers) {
this.logger.log('Sorted drivers fetched from cache');
return cachedSortedDrivers;
}

try {
const drivers = await this.findAllDrivers();
const order = [
Expand All @@ -52,7 +79,8 @@ export class DriverService {
DriverStatus.THREE_SET_AVAILABLE,
];
const sortedDrivers = this.sortDriversByStatus(drivers, order);

await this.cacheManager.set(cacheKey, sortedDrivers, 600 ); // cache for 10 minutes
this.logger.log('Sorted drivers fetched from database and cached');
return sortedDrivers;
} catch (error) {
this.logger.error(`Error while fetching and sorting drivers: ${error.message}`);
Expand Down
5 changes: 5 additions & 0 deletions apps/user/src/user.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { UserType } from './model/user.type';
import { UserTypeController } from './services/user.type.controller';
import { UserTypeService } from './services/user.type.service';
import { ClientsModule, Transport } from '@nestjs/microservices';
import { CacheModule } from '@nestjs/cache-manager';

dotenv.config();

Expand All @@ -34,6 +35,10 @@ dotenv.config();
},
},
]),
CacheModule.register({
ttl: 60, // seconds
max: 100, // maximum number of items in cache
}),
],
controllers: [UserController, UserTypeController],
providers: [UserService, UserTypeService]
Expand Down
27 changes: 24 additions & 3 deletions apps/user/src/user.service.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { Injectable, Logger } from '@nestjs/common';
import { Inject, Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './model/user.entity';
import { Cache } from 'cache-manager';
import { Repository } from 'typeorm';
import { ExceptionPayloadFactory } from '@app/shared/exception/exception.payload.factory';
import { throwException } from '@app/shared/exception/exception.util';
import { UserCreateCommand } from '@app/shared/commands/auth/user.create.cmd';
import { hashPassword } from '@app/shared/utils/hash.pass';
import { validateCommand } from '@app/shared/utils/validate';
import { ClientProxy, ClientProxyFactory, Transport } from '@nestjs/microservices';
import { CACHE_MANAGER } from '@nestjs/cache-manager';



Expand All @@ -20,6 +22,8 @@ export class UserService {
constructor(
@InjectRepository(User)
private readonly userRepository: Repository<User>,
@Inject(CACHE_MANAGER)
private cacheManager: Cache,
) {
this.driverServiceClient = ClientProxyFactory.create({
transport: Transport.TCP, // Choose your transport protocol
Expand Down Expand Up @@ -76,24 +80,41 @@ export class UserService {
}
async findUserById(id: string): Promise<User> {
this.logger.log(`Begin fetching user with id ${id}`);

const cachedUser = await this.cacheManager.get<User>(`user-${id}`);
if (cachedUser) {
this.logger.log(`User fetched from cache with id ${id}`);
return cachedUser;
}

const user = await this.userRepository.findOne({ where: {id}});

if(!user){
if (!user) {
this.logger.error(`User with id ${id} not found`);
throwException(ExceptionPayloadFactory.USER_NAME_NOT_FOUND);
}

this.logger.log(`User fetched successfully with id ${id}`);
await this.cacheManager.set(`user-${id}`, user, 600); // cache for 10 minutes
return user;
}
async getAll(): Promise<User[]> {
this.logger.log(`Begin fetching users`);

const cachedUsers = await this.cacheManager.get<User[]>('all-users');
if (cachedUsers) {
this.logger.log(`Users fetched from cache`);
return cachedUsers;
}

try {
const users = await this.userRepository.find();
this.logger.log(`Fetched users: ${JSON.stringify(users)}`);
await this.cacheManager.set('all-users', users, 600 ); // cache for 10 minutes
return users;
} catch (error) {
this.logger.error('Error fetching all users:', error.message);
throw error;
}
}
}
}
2 changes: 2 additions & 0 deletions apps/user/test/app.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { UserModule } from './../src/user.module';



describe('UserController (e2e)', () => {
let app: INestApplication;

Expand Down
Loading