const OSS = require('ali-oss');
import { OpResult, logger } from 'mslib';

/**
 * 阿里云 OSS 客户端
 * @date 2021-10-22 09:48:32
 * @author 吴锋霖
 */
export class OSSClient {

    private client;

    constructor(region: string, accessKeyId: string, accessKeySecret: string, bucket: string, ) {
        this.client = new OSS({ region, accessKeyId, accessKeySecret, bucket });
    }

    /**
     * 上传文件至OSS
     * @param name 名称
     * @param file 文件 String(文件路径，不支持目录)|Buffer|ReadStream
     */
    async upload(name: string, file: any): Promise<OpResult<string>> {
        const result = await this.client.put(name, file);
        logger.info('oss put-------->%j', result)
        if (!result) {
            return OpResult.error('OSS文件上传失败')
        }
        if (result.res.status === 200) {
            return OpResult.success("文件上传成功", { result })
        } else {
            return OpResult.error(result.res.statusMessage)
        }
    }


}