Skip to content

Commit

Permalink
Merge pull request #71 from VentionCapstone/feat/117_add-cache
Browse files Browse the repository at this point in the history
Feat/117 add cache
  • Loading branch information
Zach13131 authored Feb 10, 2024
2 parents 032fd61 + e3ea3fd commit 8f28b6f
Show file tree
Hide file tree
Showing 5 changed files with 140 additions and 6 deletions.
44 changes: 44 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"dependencies": {
"@nestjs-modules/mailer": "^1.9.1",
"@nestjs/axios": "^3.0.1",
"@nestjs/cache-manager": "^2.2.1",
"@nestjs/common": "^10.0.0",
"@nestjs/config": "^3.1.1",
"@nestjs/core": "^10.0.0",
Expand All @@ -50,6 +51,7 @@
"axios": "^1.6.5",
"base64url": "^3.0.1",
"bcryptjs": "^2.4.3",
"cache-manager": "^5.4.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"cookie-parser": "^1.4.6",
Expand Down
23 changes: 23 additions & 0 deletions src/accommodation/accommodation.cache.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Injectable, OnApplicationBootstrap } from '@nestjs/common';
import { AccommodationService } from './accommodation.service';
import { OrderAndFilterDto } from './dto/orderAndFilter.dto';

const { CACHING_PAGES, CACHING_PAGES_LIMIT } = process.env;
const CachingPages = parseInt(CACHING_PAGES!);
const CachingPagesLimit = parseInt(CACHING_PAGES_LIMIT!);

@Injectable()
export class CacheService implements OnApplicationBootstrap {
constructor(private accommodationService: AccommodationService) {}

async onApplicationBootstrap() {
await this.cacheMainPages();
}

async cacheMainPages() {
for (let page = 1; page <= CachingPages; page++) {
const options: OrderAndFilterDto = { page, limit: CachingPagesLimit };
await this.accommodationService.getAllAccommodations(options);
}
}
}
14 changes: 12 additions & 2 deletions src/accommodation/accommodation.module.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
import { HttpModule } from '@nestjs/axios';
import { CacheModule } from '@nestjs/cache-manager';
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PrismaModule } from 'src/prisma/prisma.module';
import { CacheService } from './accommodation.cache.service';
import { AccommodationController } from './accommodation.controller';
import { AccommodationService } from './accommodation.service';

const { CACHE_TIMEOUT } = process.env;
const CacheTimeout = parseInt(CACHE_TIMEOUT!);

@Module({
imports: [PrismaModule, JwtModule.register({}), HttpModule],
imports: [
PrismaModule,
JwtModule.register({}),
HttpModule,
CacheModule.register({ ttl: CacheTimeout }),
],
controllers: [AccommodationController],
providers: [AccommodationService],
providers: [AccommodationService, CacheService],
})
export class AccommodationModule {}
63 changes: 59 additions & 4 deletions src/accommodation/accommodation.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import { HttpService } from '@nestjs/axios';
import { BadRequestException, HttpException, Injectable, NotFoundException } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import {
BadRequestException,
HttpException,
Inject,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { AxiosError } from 'axios';
import { Cache } from 'cache-manager';
import * as dayjs from 'dayjs';
import { catchError, firstValueFrom } from 'rxjs';
import { Currency } from 'src/enums/currency.enum';
Expand All @@ -13,7 +21,6 @@ import { PrismaService } from 'src/prisma/prisma.service';
import { OrderAndFilterReviewDto, reviewOrderBy } from './dto/get-review.dto';
import { GetUserAccommodationsDto } from './dto/get-user-accommodations.dto';
import { OrderAndFilterDto, OrderBy } from './dto/orderAndFilter.dto';

interface UploadImageType {
mimetype: string;
base64Image: string;
Expand All @@ -27,11 +34,23 @@ interface UploadImageResponse {
};
}

const {
ACCOMMODATION_MAX_PRICE,
ACCOMMODATION_MAX_PEOPLE,
ACCOMMODATION_MAX_ROOMS,
CACHING_PAGES_LIMIT,
} = process.env;
const AccommodationMaxPrice = parseInt(ACCOMMODATION_MAX_PRICE!);
const AccommodationMaxPeople = parseInt(ACCOMMODATION_MAX_PEOPLE!);
const AccommodationMaxRooms = parseInt(ACCOMMODATION_MAX_ROOMS!);
const CachingPagesLimit = parseInt(CACHING_PAGES_LIMIT!);

@Injectable()
export class AccommodationService {
constructor(
private readonly prisma: PrismaService,
private readonly httpService: HttpService
private readonly httpService: HttpService,
@Inject(CACHE_MANAGER) private cacheManager: Cache
) {}

async createAccommodation(createAccommodationBody: any) {
Expand Down Expand Up @@ -422,6 +441,14 @@ export class AccommodationService {

async getAllAccommodations(options: OrderAndFilterDto, userId?: string) {
try {
const { page, limit } = options;
const key = `accommodations?page=${page}&limit=${limit}`;
const dataFromCache = await this.cacheManager.get(key);

if (dataFromCache) {
return dataFromCache;
}

const findManyOptions = this.generateFindAllQueryObj(options);

this.updateQueryWithSearchOptions(findManyOptions, options);
Expand Down Expand Up @@ -479,11 +506,18 @@ export class AccommodationService {
_max: { price: totalMaxPrice },
} = totalPriceStats;

return {
const isDefaultOptions = this.isDefaultOptions(options);
const resultObj = {
priceRange: { curMinPrice, curMaxPrice, totalMinPrice, totalMaxPrice },
totalCount,
data: accommodationsWithWishlist,
};

if (isDefaultOptions) {
await this.cacheManager.set(key, resultObj);
}

return resultObj;
} catch (error) {
if (error instanceof HttpException) throw error;
throw new GlobalException(ErrorsTypes.ACCOMMODATION_FAILED_TO_GET_LIST, error.message);
Expand Down Expand Up @@ -809,4 +843,25 @@ export class AccommodationService {

return orderingObjsArray;
}

private isDefaultOptions(options: OrderAndFilterDto): boolean {
const {
limit = CachingPagesLimit,
minPrice = 0,
maxPrice = AccommodationMaxPrice,
minRooms = 0,
maxRooms = AccommodationMaxRooms,
minPeople = 0,
maxPeople = AccommodationMaxPeople,
} = options;
return (
limit === CachingPagesLimit &&
minPrice === 0 &&
maxPrice === AccommodationMaxPrice &&
minRooms === 0 &&
maxRooms === AccommodationMaxRooms &&
minPeople === 0 &&
maxPeople === AccommodationMaxPeople
);
}
}

0 comments on commit 8f28b6f

Please sign in to comment.