oak-general-business/lib/utils/cos/tencent.js

99 lines
3.6 KiB
JavaScript

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const assert_1 = require("oak-domain/lib/utils/assert");
const Exception_1 = require("../../types/Exception");
const Exception_2 = require("oak-domain/lib/types/Exception");
// TODO 腾讯云上传代码未测试
class TencentYun {
name = 'tencent';
autoInform() {
return false;
}
getConfig(application) {
const { system } = application;
const { config } = system;
const tencentConfig = config.Cos?.tencent;
(0, assert_1.assert)(tencentConfig);
const { accessKey } = tencentConfig;
const account = config.Account?.tencent?.find((ele) => ele.secretId === accessKey);
(0, assert_1.assert)(account);
return {
config: tencentConfig,
account,
};
}
formKey(extraFile) {
const { id, extension, objectId } = extraFile;
(0, assert_1.assert)(objectId);
return `extraFile/${objectId}${extension ? '.' + extension : ''}`;
}
async upload(options) {
const { extraFile, uploadFn, file, uploadToAspect, getPercent } = options;
const uploadMeta = extraFile.uploadMeta;
(0, assert_1.assert)(extraFile.enableChunkedUpload !== true, '暂不支持分片上传');
let response;
try {
response = await uploadFn({
file,
name: 'file',
uploadUrl: uploadMeta.uploadHost,
formData: {
key: uploadMeta.key,
policy: uploadMeta.policy,
signature: uploadMeta.signature,
'q-sign-algorithm': uploadMeta.algorithm,
'q-ak': uploadMeta.accessKey,
'q-key-time': uploadMeta.keyTime,
'q-signature': uploadMeta.signature,
},
autoInform: true,
getPercent,
uploadId: extraFile.id
});
}
catch (err) {
// 网络错误
throw new Exception_2.OakNetworkException('网络异常,请求失败');
}
let isSuccess = false;
if (process.env.OAK_PLATFORM === 'wechatMp') {
// 小程序端上传 使用wx.uploadFile
// 待测试
if (response.errMsg === 'uploadFile:ok') {
const data = JSON.parse(response.data);
isSuccess = !!(data.status === 204);
}
}
else {
isSuccess = !!(response.status === 204);
}
// 解析回调
if (isSuccess) {
return;
}
throw new Exception_1.OakUploadException('文件上传腾讯云失败');
}
composeFileUrl(options) {
const { application, extraFile, style } = options;
const { config: tencentCosConfig } = this.getConfig(application);
if (tencentCosConfig) {
let bucket = tencentCosConfig.buckets.find((ele) => ele.name === extraFile.bucket);
if (bucket) {
const { domain, protocol } = bucket;
let protocol2 = protocol;
if (protocol instanceof Array) {
// protocol存在https: 说明域名有证书
const index = protocol.includes('https:')
? protocol.findIndex((ele) => ele === 'https:')
: 0;
protocol2 = protocol[index];
}
return `${protocol2}//${domain}/${this.formKey(extraFile)}${style ? style : ''}`;
}
}
return '';
}
}
exports.default = TencentYun;
;