@szmg-fe/tarco
Version:
function library in Taro
85 lines (74 loc) • 2.99 kB
text/typescript
/*
* @Description: hook of cos
* @Date: 2021-03-22 17:39:09
* @Author: Lemon
* @LastEditTime: 2021-05-21 17:26:39
*/
import { useRef } from "react";
import COS from 'cos-wx-sdk-v5';
import { compose } from "@szmg-fe/funba/ramda";
import { useFinishRender } from "@szmg-fe/hooks/useEffect";
import useRefCallback from "@szmg-fe/hooks/useRefCallback";
import Task from 'data.task';
import randomString from "@szmg-fe/funba/random";
import hideLoading from "./hideLoading";
import fork from "@szmg-fe/funba/fork";
import { error } from '@szmg-fe/funba/console'
/**
* 小程序专用
* @param http: (params) => task
* @returns cos ref
*/
export default function useCos(http: Task) {
const cosObj = useRef<any>({});
const credentials = useRef<any>({});
const saveObj = res => {
cosObj.current = new COS({
getAuthorization: function (options, callback) {
console.log(options);
// 异步获取临时密钥
callback({
TmpSecretId: res.credentials.tmpSecretId,
TmpSecretKey: res.credentials.tmpSecretKey,
XCosSecurityToken: res.credentials.sessionToken,
// 建议返回服务器时间作为签名的开始时间,避免用户浏览器本地时间偏差过大导致签名错误
StartTime: res.startTime, // 时间戳,单位秒,如:1580000000
ExpiredTime: res.expiredTime, // 时间戳,单位秒,如:1580000900
});
}
});
credentials.current = res;
}
const initCosParams = () => ({ durationSeconds: 3600 * 12, type: 'OBJECT_UPLOAD' });
const initCos = compose(fork(error, saveObj), http, initCosParams);
useFinishRender(initCos);
const upload = useRefCallback(tempFilePath => {
const randomName = randomString(16); // 16位随机码作为文件名
return new Task((rej, resolve) => {
const key = credentials.current.allowPrefix.replace(/\*/, `${randomName}${tempFilePath.match(/\.(\w+)/)[0]}`);
cosObj.current.postObject({
Bucket: credentials.current.bucket,
Region: credentials.current.region,
Key: key,
FilePath: tempFilePath,
onProgress: info => {
console.log('uploading cos', JSON.stringify(info));
// showLoading("上传中 " + info.percent * 100 + "%");
}
}, function (err, data) {
if (err) {
rej(err);
}
if (data) {
resolve({
key, // 腾讯云不返回key 需要手动返回
url: `https://${data.Location}`,
type: 'image'
});
}
hideLoading();
});
});
})
return upload;
}