Browse Source

refactor(video): streamline method signatures and remove redundant code

Dave 1 month ago
parent
commit
b2b9572bc3

+ 7 - 17
apps/box-app-api/src/feature/video/video.controller.ts

@@ -44,9 +44,7 @@ interface RequestWithUser extends Request {
 @ApiTags('视频')
 @Controller('video')
 export class VideoController {
-  constructor(private readonly videoService: VideoService
-  ) {}
-  
+  constructor(private readonly videoService: VideoService) {}
 
   /**
    * GET /api/v1/video/search
@@ -57,8 +55,6 @@ export class VideoController {
   @ApiOperation({
     summary: '搜索视频',
     description: '',
-    summary: '搜索视频',
-    description: '',
   })
   @ApiResponse({
     status: 200,
@@ -66,9 +62,7 @@ export class VideoController {
     type: VideoItemDto,
     isArray: true,
   })
-  async search(
-    @Body() req: VideoListRequestDto,
-  ): Promise<VideoItemDto[]> {
+  async search(@Body() req: VideoListRequestDto): Promise<VideoItemDto[]> {
     return await this.videoService.getVideoList(req);
   }
 
@@ -86,13 +80,11 @@ export class VideoController {
     description: '标签+视频',
     isArray: true,
   })
-  async homeVideo(
-    @Query('channelId') channelId: string,
-  ): Promise<any[]> {
+  async homeVideo(@Query('channelId') channelId: string): Promise<any[]> {
     return await this.videoService.getHomeSectionVideos(channelId);
-  }  
+  }
 
-@Get('guess')
+  @Get('guess')
   @ApiOperation({
     summary: '猜你喜欢',
   })
@@ -106,11 +98,9 @@ export class VideoController {
     description: '视频',
     isArray: true,
   })
-  async guess(
-    @Query('tag') tag: string,
-  ): Promise<any[]> {
+  async guess(@Query('tag') tag: string): Promise<any[]> {
     return await this.videoService.getGuessLikeVideos(tag);
-  }    
+  }
 
   /**
    * GET /api/v1/video/latest

+ 38 - 41
apps/box-app-api/src/feature/video/video.service.ts

@@ -37,7 +37,6 @@ import {
 } from '../homepage/homepage.constants';
 import { CategoryDto } from '../homepage/dto/homepage.dto';
 import { VideoListItemDto } from './dto/video-list-response.dto';
-import { VideoListItemDto } from './dto/video-list-response.dto';
 
 /**
  * VideoService provides read-only access to video data from Redis cache.
@@ -65,9 +64,7 @@ export class VideoService {
    * Reads from appVideoHomeSectionKey (LIST of videoIds).
    * Returns video details for each ID.
    */
-  async getHomeSectionVideos(
-    channelId: string
-  ): Promise<any[]> {
+  async getHomeSectionVideos(channelId: string): Promise<any[]> {
     try {
       const channel = await this.mongoPrisma.channel.findUnique({
         where: { channelId },
@@ -76,11 +73,14 @@ export class VideoService {
       const result: { tag: string; records: VideoListItemDto[] }[] = [];
 
       for (const tag of channel.tagNames) {
-        const records = await this.getVideoList({
-          random: true,
-          tag,
-          size: 7,
-        }, 3600 * 24);
+        const records = await this.getVideoList(
+          {
+            random: true,
+            tag,
+            size: 7,
+          },
+          3600 * 24,
+        );
 
         result.push({
           tag,
@@ -103,18 +103,18 @@ export class VideoService {
    * Reads video IDs from Redis cache, fetches full details from MongoDB,
    * and returns paginated results.
    */
-  async getVideoList(dto: VideoListRequestDto, ttl?: number): Promise<VideoListItemDto[]> {
+  async getVideoList(
+    dto: VideoListRequestDto,
+    ttl?: number,
+  ): Promise<VideoListItemDto[]> {
     const { page, size, tag, keyword, random } = dto;
     const start = (page - 1) * size;
 
-    const cacheKey = `video:list:${Buffer.from(
-      JSON.stringify(dto),
-    ).toString('base64')}`;
-    const cacheKey = `video:list:${Buffer.from(
-      JSON.stringify(dto),
-    ).toString('base64')}`;
+    const cacheKey = `video:list:${Buffer.from(JSON.stringify(dto)).toString(
+      'base64',
+    )}`;
 
-    if(!ttl){
+    if (!ttl) {
       ttl = random ? 15 : 300;
     }
 
@@ -125,11 +125,11 @@ export class VideoService {
         return cache;
       }
 
-      let where: any = {
-        status: 'Completed'
+      const where: any = {
+        status: 'Completed',
       };
 
-      if(random){
+      if (random) {
         if (tag) {
           where.secondTags = tag;
         }
@@ -138,7 +138,7 @@ export class VideoService {
           where.title = {
             $regex: keyword,
             $options: 'i',
-          }
+          };
         }
 
         fallbackRecords = (await this.mongoPrisma.videoMedia.aggregateRaw({
@@ -157,7 +157,7 @@ export class VideoService {
             },
           ],
         })) as unknown as VideoListItemDto[];
-      }else{
+      } else {
         if (tag) {
           where.secondTags = {
             has: tag,
@@ -166,8 +166,9 @@ export class VideoService {
 
         if (keyword) {
           where.title = {
-            contains: keyword, mode: 'insensitive'
-          }
+            contains: keyword,
+            mode: 'insensitive',
+          };
         }
 
         fallbackRecords = (await this.mongoPrisma.videoMedia.findMany({
@@ -175,8 +176,6 @@ export class VideoService {
           orderBy: [{ addedTime: 'desc' }, { createdAt: 'desc' }],
           skip: start,
           take: size,
-          skip: start,
-          take: size,
           select: {
             id: true,
             title: true,
@@ -186,13 +185,10 @@ export class VideoService {
             preFileName: true,
           },
         })) as VideoListItemDto[];
-        })) as VideoListItemDto[];
       }
 
       if (fallbackRecords.length > 0) {
         await this.redis.setJson(cacheKey, fallbackRecords, ttl);
-      if (fallbackRecords.length > 0) {
-        await this.redis.setJson(cacheKey, fallbackRecords, ttl);
       }
 
       return fallbackRecords;
@@ -203,14 +199,6 @@ export class VideoService {
       );
       return [];
     }
-      return fallbackRecords;
-    } catch (err) {
-      this.logger.error(
-        `Error fetching videos from MongoDB`,
-        err instanceof Error ? err.stack : String(err),
-      );
-      return [];
-    }
   }
 
   /**
@@ -486,7 +474,10 @@ export class VideoService {
   async getGuessLikeVideos(tag: string): Promise<VideoItemDto[]> {
     try {
       // Try to fetch from Redis cache first
-      const cached = await this.readCachedVideoList(tsCacheKeys.video.guess() + encodeURIComponent(tag), 'guess like videos');
+      const cached = await this.readCachedVideoList(
+        tsCacheKeys.video.guess() + encodeURIComponent(tag),
+        'guess like videos',
+      );
 
       if (cached && Array.isArray(cached) && cached.length > 0) {
         return cached;
@@ -508,9 +499,15 @@ export class VideoService {
         this.mapVideoToDto(v),
       );
 
-      this.redis.setJson(tsCacheKeys.video.guess() + encodeURIComponent(tag), items, 3600).catch(err => {
-        this.logger.warn("Redis setJson video.guess failed", err);
-      });
+      this.redis
+        .setJson(
+          tsCacheKeys.video.guess() + encodeURIComponent(tag),
+          items,
+          3600,
+        )
+        .catch((err) => {
+          this.logger.warn('Redis setJson video.guess failed', err);
+        });
 
       return items;
     } catch (error) {