ad.controller.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // apps/box-app-api/src/feature/ads/ad.controller.ts
  2. import {
  3. Controller,
  4. Get,
  5. Logger,
  6. Query,
  7. Post,
  8. Body,
  9. Param,
  10. UseGuards,
  11. Req,
  12. NotFoundException,
  13. UnauthorizedException,
  14. } from '@nestjs/common';
  15. import {
  16. ApiOperation,
  17. ApiResponse,
  18. ApiTags,
  19. ApiBearerAuth,
  20. } from '@nestjs/swagger';
  21. import { Request } from 'express';
  22. import { AdService } from './ad.service';
  23. import { GetAdPlacementQueryDto } from './dto/get-ad-placement.dto';
  24. import { AdDto } from './dto/ad.dto';
  25. import {
  26. AdListRequestDto,
  27. AdListResponseDto,
  28. AdClickDto,
  29. AdImpressionDto,
  30. AllAdsResponseDto,
  31. } from './dto';
  32. import { AdUrlResponseDto } from './dto/ad-url-response.dto';
  33. import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
  34. // Extend Express Request to include user from JWT
  35. interface JwtUser {
  36. uid: string;
  37. sub: string;
  38. jti: string;
  39. }
  40. interface RequestWithUser extends Request {
  41. user: JwtUser;
  42. }
  43. @ApiTags('广告')
  44. @Controller('ads')
  45. export class AdController {
  46. private readonly logger = new Logger(AdController.name);
  47. constructor(private readonly adService: AdService) {}
  48. /**
  49. * POST /api/v1/ads/list
  50. *
  51. * List ads by type with pagination.
  52. * Request body contains page, size, and adType.
  53. * Returns paginated list of ads with metadata.
  54. */
  55. @Post('list')
  56. @ApiOperation({
  57. summary: '获取所有广告类型及广告列表',
  58. description:
  59. '获取所有广告类型(从系统参数)以及按广告类型分组的广告列表。支持分页。数据来源:Mongo Ads 模型 + 系统参数。',
  60. })
  61. @ApiResponse({
  62. status: 200,
  63. description: '成功返回所有广告类型和分组广告列表',
  64. type: AllAdsResponseDto,
  65. })
  66. async listAdsByType(@Body() req: AdListRequestDto): Promise<any> {
  67. const { page, size } = req;
  68. this.logger.debug(`listAdsByType: page=${page}, size=${size}`);
  69. const response = await this.adService.listAdsByType(page, size);
  70. return response;
  71. }
  72. private getClientIp(req: Request): string {
  73. return (
  74. (req.headers['x-forwarded-for'] as string)?.split(',')[0]?.trim() ||
  75. (req.headers['x-real-ip'] as string) ||
  76. req.ip ||
  77. req.socket?.remoteAddress ||
  78. 'unknown'
  79. );
  80. }
  81. private getUserAgent(req: Request): string {
  82. return (req.headers['user-agent'] as string) || 'unknown';
  83. }
  84. }