67 lines
1.8 KiB
JavaScript
67 lines
1.8 KiB
JavaScript
import { request } from "@cqsjjb/jjb-common-lib/http";
|
|
import { useState } from "react";
|
|
import { UPLOAD_FILE_TYPE_ENUM } from "../../enum/uploadFile/gwj";
|
|
import { addingPrefixToFile } from "../../utils";
|
|
|
|
/**
|
|
* 获取文件
|
|
*/
|
|
function useGetFile(returnType = "object") {
|
|
// loading状态
|
|
const [loading, setLoading] = useState(false);
|
|
// 用于跟踪进行中的请求数量(不暴露给外部)
|
|
let requestCount = 0;
|
|
|
|
// 获取文件
|
|
const getFile = (options) => {
|
|
if (!options)
|
|
throw new Error("请传入 options");
|
|
|
|
// 增加请求数量并设置loading状态
|
|
requestCount++;
|
|
if (requestCount > 0) {
|
|
setLoading(true);
|
|
}
|
|
|
|
return new Promise((resolve, reject) => {
|
|
const { eqType, eqForeignKey } = options;
|
|
|
|
if (!eqType)
|
|
throw new Error("请传入 options.eqType");
|
|
|
|
// 检查eqType是否在UPLOAD_FILE_TYPE_ENUM中
|
|
if (!Object.values(UPLOAD_FILE_TYPE_ENUM).includes(eqType))
|
|
throw new Error("传入的 eqType 不在 UPLOAD_FILE_TYPE_ENUM 中");
|
|
|
|
if (eqForeignKey === undefined || eqForeignKey === null)
|
|
throw new Error("请传入 options.eqForeignKey");
|
|
|
|
// 发送请求
|
|
request(
|
|
"/basic-info/imgFiles/listAll",
|
|
"get",
|
|
{ eqType, eqForeignKey },
|
|
)
|
|
.then((res) => {
|
|
resolve(addingPrefixToFile(res.data).map(item => ({ ...item, type: undefined })));
|
|
})
|
|
.catch((err) => {
|
|
reject(err);
|
|
})
|
|
.finally(() => {
|
|
// 减少请求数量并在没有进行中的请求时设置loading为false
|
|
requestCount--;
|
|
if (requestCount <= 0) {
|
|
setLoading(false);
|
|
}
|
|
});
|
|
});
|
|
};
|
|
|
|
if (returnType === "array")
|
|
return [loading, getFile];
|
|
return { loading, getFile };
|
|
}
|
|
|
|
export default useGetFile;
|