返回 AiToEarn
base.service.ts
1 import type { OpenApiResponse } from '@volcengine/openapi/lib/base/types'
2 import type { VodService } from '@volcengine/openapi/lib/services/vod'
3 import { Logger } from '@nestjs/common'
4 import { vodOpenapi } from '@volcengine/openapi'
5 import { AppException, ResponseCode } from '@yikart/common'
6 import { VolcengineConfig } from '../volcengine.config'
7
8 /**
9 * Volcengine 服务基类
10 * 提供共享的基础功能:配置、VodService、日志、错误处理
11 */
12 export abstract class BaseService {
13 protected readonly logger: Logger
14 protected readonly vodService: VodService
15
16 constructor(protected readonly config: VolcengineConfig) {
17 this.vodService = this.createVodService()
18 this.logger = new Logger(this.constructor.name)
19 }
20
21 /**
22 * 获取播放基础 URL
23 */
24 getPlaybackBaseUrl(): string {
25 return this.config.playbackBaseUrl
26 }
27
28 /**
29 * 获取空间名称
30 */
31 getSpaceName(): string {
32 return this.config.spaceName
33 }
34
35 /**
36 * 创建视频点播服务实例
37 */
38 protected createVodService(): VodService {
39 return new vodOpenapi.VodService({
40 accessKeyId: this.config.accessKeyId,
41 secretKey: this.config.secretAccessKey,
42 serviceName: 'vod',
43 })
44 }
45
46 /**
47 * 检查 API 响应中的错误并抛出异常
48 */
49 protected checkApiResponseError<T>(
50 response: OpenApiResponse<T>,
51 operation: string,
52 requestData?: unknown,
53 ): asserts response is OpenApiResponse<T> & { Result: T } {
54 if (response.ResponseMetadata?.Error) {
55 const error = response.ResponseMetadata.Error
56 this.logger.error(
57 { error, requestData },
58 `${operation} failed: ${error.Code || 'Unknown'} - ${error.Message}`,
59 )
60 throw new AppException(ResponseCode.AiCallFailed, {
61 code: error.Code || 'Unknown',
62 message: error.Message,
63 })
64 }
65
66 if (!response.Result) {
67 this.logger.error({ requestData }, `${operation} returned no result`)
68 throw new AppException(ResponseCode.AiCallFailed, {
69 message: typeof response === 'string' ? response : 'No result returned',
70 })
71 }
72 }
73 }
74
74 lines TYPESCRIPT