返回 AiToEarn
ali-oss.service.ts
根目录 / project / aitoearn-backend / libs / ali-oss / src / ali-oss.service.ts
1 import { Injectable, Logger } from '@nestjs/common'
2 import { AppException, ResponseCode } from '@yikart/common'
3 import OSS from 'ali-oss'
4 import { AliOssConfig } from './ali-oss.config'
5
6 @Injectable()
7 export class AliOssService {
8 private readonly logger = new Logger(AliOssService.name)
9
10 constructor(
11 private readonly config: AliOssConfig,
12 private readonly client: OSS,
13 ) {}
14
15 getClient(): OSS {
16 return this.client
17 }
18
19 async putObject(key: string, file: Buffer | string, options?: OSS.PutObjectOptions) {
20 return await this.client.put(key, file, options)
21 }
22
23 async putObjectFromUrl(url: string, objectPath: string) {
24 try {
25 await this.client.head(objectPath)
26 return { path: objectPath, exists: true }
27 }
28 catch {
29 const response = await fetch(url)
30 if (response.body === null) {
31 throw new AppException(ResponseCode.S3DownloadFileFailed)
32 }
33 const buffer = Buffer.from(await response.arrayBuffer())
34 const contentType = response.headers.get('content-type') || undefined
35 const options: OSS.PutObjectOptions = contentType ? { headers: { 'Content-Type': contentType } } : {}
36 await this.client.put(objectPath, buffer, options)
37 return { path: objectPath }
38 }
39 }
40
41 async getObject(key: string) {
42 return await this.client.get(key)
43 }
44
45 async deleteObject(key: string) {
46 return await this.client.delete(key)
47 }
48
49 async listObjects(query: OSS.ListObjectsQuery, options?: OSS.RequestOptions) {
50 return await this.client.list(query, options ?? {})
51 }
52
53 async getSignUrl(key: string, options?: OSS.SignatureUrlOptions) {
54 return this.client.signatureUrl(key, options)
55 }
56
57 getUploadSignUrl(key: string, contentType?: string, trafficLimit?: number, callback?: OSS.ObjectCallback): string {
58 return this.client.signatureUrl(key, {
59 'method': 'PUT',
60 'expires': this.config.signExpires,
61 'Content-Type': contentType,
62 trafficLimit,
63 ...(callback ? { callback } : {}),
64 })
65 }
66
67 async headObject(key: string) {
68 return await this.client.head(key)
69 }
70
71 async copyObject(
72 objectPath: string,
73 options: {
74 contentType?: string
75 contentDisposition?: string
76 metadata?: Record<string, string>
77 },
78 ) {
79 const headers: Record<string, string> = {}
80 if (options.contentType)
81 headers['Content-Type'] = options.contentType
82 if (options.contentDisposition)
83 headers['Content-Disposition'] = options.contentDisposition
84 const copyOptions: OSS.CopyObjectOptions = {
85 headers,
86 meta: options.metadata as OSS.UserMeta | undefined,
87 }
88 await this.client.copy(objectPath, objectPath, copyOptions)
89 }
90 }
91
91 lines TYPESCRIPT