返回 AiToEarn
s3.module.ts
根目录 / project / aitoearn-backend / libs / aws-s3 / src / s3.module.ts
1 import type { DynamicModule, Provider } from '@nestjs/common'
2 import { S3Client } from '@aws-sdk/client-s3'
3 import { Global, Module } from '@nestjs/common'
4 import { S3Config } from './s3.config'
5 import { S3_SIGNING_CLIENT } from './s3.constants'
6 import { S3Service } from './s3.service'
7
8 @Global()
9 @Module({})
10 export class S3Module {
11 static forRoot(config: S3Config): DynamicModule {
12 const buildCredentials = (s3Config: S3Config) =>
13 s3Config.accessKeyId && s3Config.secretAccessKey
14 ? { accessKeyId: s3Config.accessKeyId, secretAccessKey: s3Config.secretAccessKey }
15 : undefined
16
17 const providers: Provider[] = [
18 {
19 provide: S3Config,
20 useValue: config,
21 },
22 {
23 provide: S3Client,
24 useFactory: (s3Config: S3Config) => new S3Client({
25 region: s3Config.region,
26 endpoint: s3Config.endpoint,
27 forcePathStyle: s3Config.forcePathStyle,
28 credentials: buildCredentials(s3Config),
29 }),
30 inject: [S3Config],
31 },
32 {
33 provide: S3_SIGNING_CLIENT,
34 useFactory: (s3Config: S3Config) => new S3Client({
35 region: s3Config.region,
36 endpoint: s3Config.publicEndpoint || s3Config.endpoint,
37 forcePathStyle: s3Config.forcePathStyle,
38 credentials: buildCredentials(s3Config),
39 }),
40 inject: [S3Config],
41 },
42 S3Service,
43 ]
44
45 return {
46 global: true,
47 module: S3Module,
48 providers,
49 exports: [S3Service],
50 }
51 }
52 }
53
53 lines TYPESCRIPT