Skip to content

Commit

Permalink
refactor(api): optimize user cache implementation and improve code st…
Browse files Browse the repository at this point in the history
…ructure
  • Loading branch information
Z-xus committed Jul 29, 2024
1 parent e99c6c9 commit dbdb568
Show file tree
Hide file tree
Showing 7 changed files with 31 additions and 18 deletions.
4 changes: 3 additions & 1 deletion apps/api/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { ScheduleModule } from '@nestjs/schedule'
import { EnvSchema } from '../common/env/env.schema'
import { IntegrationModule } from '../integration/integration.module'
import { FeedbackModule } from '../feedback/feedback.module'
import { CacheModule } from '../cache/cache.module'

@Module({
controllers: [AppController],
Expand Down Expand Up @@ -53,7 +54,8 @@ import { FeedbackModule } from '../feedback/feedback.module'
SocketModule,
ProviderModule,
IntegrationModule,
FeedbackModule
FeedbackModule,
CacheModule
],
providers: [
{
Expand Down
4 changes: 1 addition & 3 deletions apps/api/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { GoogleOAuthStrategyFactory } from '../config/factory/google/google-stra
import { GoogleStrategy } from '../config/oauth-strategy/google/google.strategy'
import { GitlabOAuthStrategyFactory } from '../config/factory/gitlab/gitlab-strategy.factory'
import { GitlabStrategy } from '../config/oauth-strategy/gitlab/gitlab.strategy'
import { CacheModule } from '../cache/cache.module'

@Module({
imports: [
Expand All @@ -22,8 +21,7 @@ import { CacheModule } from '../cache/cache.module'
algorithm: 'HS256'
}
}),
UserModule,
CacheModule
UserModule
],
providers: [
AuthService,
Expand Down
4 changes: 3 additions & 1 deletion apps/api/src/auth/controller/auth.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { ConfigService } from '@nestjs/config'
import { GithubOAuthStrategyFactory } from '../../config/factory/github/github-strategy.factory'
import { GoogleOAuthStrategyFactory } from '../../config/factory/google/google-strategy.factory'
import { GitlabOAuthStrategyFactory } from '../../config/factory/gitlab/gitlab-strategy.factory'
import { CacheService } from '../../cache/cache.service'

describe('AuthController', () => {
let controller: AuthController
Expand All @@ -25,7 +26,8 @@ describe('AuthController', () => {
ConfigService,
{ provide: MAIL_SERVICE, useClass: MockMailService },
JwtService,
PrismaService
PrismaService,
CacheService
]
})
.overrideProvider(PrismaService)
Expand Down
1 change: 0 additions & 1 deletion apps/api/src/auth/guard/auth/auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,6 @@ export class AuthGuard implements CanActivate {
throw new UnauthorizedException('Onboarding not finished')
}

if (user) this.cache.setUser(user)
// We attach the user to the request object.
request['user'] = user
return true
Expand Down
4 changes: 3 additions & 1 deletion apps/api/src/auth/service/auth.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { MAIL_SERVICE } from '../../mail/services/interface.service'
import { JwtService } from '@nestjs/jwt'
import { PrismaService } from '../../prisma/prisma.service'
import { mockDeep } from 'jest-mock-extended'
import { CacheService } from '../../cache/cache.service'

describe('AuthService', () => {
let service: AuthService
Expand All @@ -15,7 +16,8 @@ describe('AuthService', () => {
AuthService,
{ provide: MAIL_SERVICE, useClass: MockMailService },
JwtService,
PrismaService
PrismaService,
CacheService
]
})
.overrideProvider(PrismaService)
Expand Down
6 changes: 4 additions & 2 deletions apps/api/src/auth/service/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { PrismaService } from '../../prisma/prisma.service'
import createUser from '../../common/create-user'
import { AuthProvider } from '@prisma/client'
import generateOtp from '../../common/generate-otp'
import { CacheService } from '../../cache/cache.service'

@Injectable()
export class AuthService {
Expand All @@ -26,7 +27,8 @@ export class AuthService {
constructor(
@Inject(MAIL_SERVICE) private mailService: IMailService,
private readonly prisma: PrismaService,
private jwt: JwtService
private jwt: JwtService,
private cache: CacheService
) {
this.logger = new Logger(AuthService.name)
}
Expand Down Expand Up @@ -82,7 +84,7 @@ export class AuthService {
}
}
})

this.cache.setUser(user) // Save user to cache
this.logger.log(`User logged in: ${email}`)

const token = await this.generateToken(user.id)
Expand Down
26 changes: 17 additions & 9 deletions apps/api/src/cache/cache.service.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,30 @@
import { Injectable, OnModuleDestroy } from '@nestjs/common'
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common'
import { createClient, RedisClientType } from 'redis'
import { User } from '@prisma/client'

@Injectable()
export class CacheService implements OnModuleDestroy {
private readonly redisClient: RedisClientType
private readonly userPrefix = 'user-'
private static readonly USER_PREFIX = 'user-'
private readonly logger = new Logger(CacheService.name)

constructor() {
this.redisClient = createClient({
url: 'redis://localhost:6379' // Replace with your Redis URL
// Add other Redis configuration options as needed
})
this.redisClient.connect()
if (process.env.REDIS_URL) {
this.redisClient = createClient({
url: process.env.REDIS_URL
})
this.redisClient.connect().catch((error) => {
this.logger.error('Failed to connect to Redis', error)
})
} else {
this.logger.warn(
'REDIS_URL is not set. CacheService will not be functional.'
)
}
}

private getUserKey(userId: string): string {
return `${this.userPrefix}${userId}`
return `${CacheService.USER_PREFIX}${userId}`
}

async setUser(user: User, expirationInSeconds?: number): Promise<void> {
Expand Down Expand Up @@ -44,7 +52,7 @@ export class CacheService implements OnModuleDestroy {
}

async clearAllUserCache(): Promise<void> {
const keys = await this.redisClient.keys(`${this.userPrefix}*`)
const keys = await this.redisClient.keys(`${CacheService.USER_PREFIX}*`)
if (keys.length > 0) {
await this.redisClient.del(keys)
}
Expand Down

0 comments on commit dbdb568

Please sign in to comment.