import { Config , Init , Inject , Provide , Scope , ScopeEnum , } from '@midwayjs/decorator' ; import * as OSS from 'ali-oss' ; import * as assert from 'assert' ; import { ServiceFactory , delegateTargetPrototypeMethod } from '@midwayjs/core' ; function checkBucketConfig ( config ) { assert ( config . endpoint || config . region , "[@midwayjs/oss] Must set `endpoint` or `region` in oss's config" ) ; assert ( config . accessKeySecret && config . accessKeyId , "[@midwayjs/oss] Must set `accessKeyId` and `accessKeySecret` in oss's config" ) ; } @ Provide ( ) @ Scope ( ScopeEnum . Singleton ) export class OSSServiceFactory < T = OSS > extends ServiceFactory < T > { @ Config ( 'oss' ) ossConfig ; @ Init ( ) async init ( ) { await this . initClients ( this . ossConfig ) ; } async createClient ( config ) { if ( config . cluster ) { config . cluster . forEach ( checkBucketConfig ) ; return new ( OSS as any ) . ClusterClient ( config ) ; } if ( config . sts === true ) { return new OSS . STS ( config ) as any ; } checkBucketConfig ( config ) ; return new OSS ( config ) as any ; } getName ( ) { return 'oss' ; } } @ Provide ( ) @ Scope ( ScopeEnum . Singleton ) export class OSSService implements OSS { @ Inject ( ) private serviceFactory : OSSServiceFactory < OSS > ; private instance : OSS ; @ Init ( ) async init ( ) { this . instance = this . serviceFactory . get ( 'default' ) ; } } export interface OSSService extends OSS { } delegateTargetPrototypeMethod ( OSSService , [ OSS ] ) ; @ Provide ( ) @ Scope ( ScopeEnum . Singleton ) export class OSSSTSService implements OSS . STS { @ Inject ( ) private serviceFactory : OSSServiceFactory < OSS . STS > ; private instance : OSS . STS ; @ Init ( ) async init ( ) { this . instance = this . serviceFactory . get ( 'default' ) ; } async assumeRole ( roleArn , policy ? , expirationSeconds ? , session ? , options ? ) { return this . instance . assumeRole ( roleArn , policy , expirationSeconds , session , options ) ; } }