|
| 1 | +import { Injectable, Logger } from '@nestjs/common'; |
| 2 | +import { S3Service } from '../s3/s3.service'; |
| 3 | +import { RedisService } from '../redis/redis.service'; |
| 4 | +import { Readable } from 'stream'; |
| 5 | +import Utils from '../helpers/utils'; |
| 6 | + |
| 7 | +const ONE_DAY = 24 * 60 * 60; |
| 8 | +const REDIS_PREFIX = 's3-cache:'; |
| 9 | +const CACHE_TIME = 30 * ONE_DAY; |
| 10 | + |
| 11 | +@Injectable() |
| 12 | +export class S3CacheService { |
| 13 | + private readonly logger = new Logger(S3CacheService.name); |
| 14 | + |
| 15 | + constructor( |
| 16 | + private readonly s3: S3Service, |
| 17 | + private readonly redis: RedisService, |
| 18 | + ) {} |
| 19 | + |
| 20 | + async getObject(key: string): Promise<Readable | null> { |
| 21 | + const cachedObject = await this.getCachedObject(key); |
| 22 | + if (cachedObject) { |
| 23 | + return cachedObject; |
| 24 | + } |
| 25 | + |
| 26 | + const object = await this.s3.getObjectBody(key); |
| 27 | + if (!object) return null; |
| 28 | + |
| 29 | + await this.cacheObject(key, object); |
| 30 | + const newObject = await this.getCachedObject(key); |
| 31 | + return newObject; |
| 32 | + } |
| 33 | + |
| 34 | + private async getCachedObject(key: string): Promise<Readable | null> { |
| 35 | + const redisKey = `${REDIS_PREFIX}${key}`; |
| 36 | + |
| 37 | + const exist = await this.redis.client.exists(redisKey); |
| 38 | + if (exist == 0) return null; |
| 39 | + |
| 40 | + const cachedObject = await this.redis.client.getBuffer(redisKey); |
| 41 | + const stream = Readable.from(cachedObject); |
| 42 | + return stream; |
| 43 | + } |
| 44 | + |
| 45 | + private async cacheObject(key: string, object: Readable): Promise<void> { |
| 46 | + const redisKey = `${REDIS_PREFIX}${key}`; |
| 47 | + |
| 48 | + const buffer = await Utils.streamToBuffer(object); |
| 49 | + await this.redis.client.set(redisKey, buffer); |
| 50 | + await this.redis.client.expire(redisKey, CACHE_TIME); |
| 51 | + this.logger.log(`Cached s3 object with key "${key}" for ${CACHE_TIME}s`); |
| 52 | + } |
| 53 | +} |
0 commit comments