返回 AiToEarn
base.service.ts
1 import { Injectable, Logger } from '@nestjs/common'
2 import { AppException, COMMON_PROPAGATION_HEADERS, CommonResponse, propagationContext } from '@yikart/common'
3 import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
4 import { AitoearnAiClientConfig } from '../aitoearn-ai-client.config'
5
6 @Injectable()
7 export class BaseService {
8 protected readonly httpClient: AxiosInstance
9 private readonly logger = new Logger(BaseService.name)
10 constructor(
11 private readonly config: AitoearnAiClientConfig,
12 ) {
13 this.httpClient = axios.create({
14 baseURL: this.config.baseUrl,
15 timeout: 30000,
16 headers: {
17 'Content-Type': 'application/json',
18 'Authorization': `Bearer ${this.config.token}`,
19 },
20 })
21
22 this.httpClient.interceptors.request.use((request) => {
23 const store = propagationContext.getStore()
24 if (store == null)
25 return request
26 COMMON_PROPAGATION_HEADERS
27 .forEach((key) => {
28 const value = store.headers[key]
29 if (value) {
30 request.headers.set(key, value)
31 }
32 })
33 return request
34 })
35
36 const resInterceptor = (response: AxiosResponse) => {
37 const res = response.data as CommonResponse<unknown>
38 if (res.code !== 0) {
39 this.logger.error({ path: this.config.baseUrl + response.config.url, ...res })
40 throw new AppException(res.code, res.message)
41 }
42 return response
43 }
44
45 this.httpClient.interceptors.response.use(resInterceptor)
46 }
47
48 async request<T = unknown>(
49 url: string,
50 config: AxiosRequestConfig = {},
51 ): Promise<T> {
52 const response: AxiosResponse<CommonResponse<T>> = await this.httpClient(url, config)
53
54 return response.data.data!
55 }
56 }
57
57 lines TYPESCRIPT