瀏覽代碼

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

This reverts commit b2b9572bc3500abdfd697ff876e3b8ad3cbbc38f.
Dave 1 月之前
父節點
當前提交
c28a21c93b

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

@@ -44,7 +44,9 @@ 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
@@ -55,6 +57,8 @@ export class VideoController {
   @ApiOperation({
     summary: '搜索视频',
     description: '',
+    summary: '搜索视频',
+    description: '',
   })
   @ApiResponse({
     status: 200,
@@ -62,7 +66,9 @@ 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);
   }
 
@@ -80,11 +86,13 @@ 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: '猜你喜欢',
   })
@@ -98,9 +106,11 @@ 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

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

@@ -37,6 +37,7 @@ 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.
@@ -64,7 +65,9 @@ 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 },
@@ -73,14 +76,11 @@ 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;
       }
 
-      const where: any = {
-        status: 'Completed',
+      let 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,9 +166,8 @@ export class VideoService {
 
         if (keyword) {
           where.title = {
-            contains: keyword,
-            mode: 'insensitive',
-          };
+            contains: keyword, mode: 'insensitive'
+          }
         }
 
         fallbackRecords = (await this.mongoPrisma.videoMedia.findMany({
@@ -176,6 +175,8 @@ export class VideoService {
           orderBy: [{ addedTime: 'desc' }, { createdAt: 'desc' }],
           skip: start,
           take: size,
+          skip: start,
+          take: size,
           select: {
             id: true,
             title: true,
@@ -185,10 +186,13 @@ 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;
@@ -199,6 +203,14 @@ export class VideoService {
       );
       return [];
     }
+      return fallbackRecords;
+    } catch (err) {
+      this.logger.error(
+        `Error fetching videos from MongoDB`,
+        err instanceof Error ? err.stack : String(err),
+      );
+      return [];
+    }
   }
 
   /**
@@ -474,10 +486,7 @@ 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;
@@ -499,15 +508,9 @@ 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) {