Files
platforms/frontend/platform_admin/src/views/resource/avatar-upload-cache.ts
2026-08-11 13:37:44 +08:00

36 lines
1.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 功能:缓存一次资源保存流程中已经完成的头像上传结果。
* 版本v1.0.0
*/
export type AvatarUpload = (file: File) => Promise<{ uri: string }>;
/** 创建头像上传缓存;选择新文件或清除头像时由调用方主动重置。 */
export function createAvatarUploadCache(upload: AvatarUpload) {
let cachedFile: File | undefined;
let cachedURI: Promise<string> | undefined;
/** 返回当前文件的受控资源地址;同一文件重试时复用首次成功结果。 */
async function resolve(file: File) {
if (cachedFile !== file || !cachedURI) {
cachedFile = file;
cachedURI = upload(file)
.then((result) => result.uri)
.catch((error) => {
// 上传本身失败时清空缓存,允许用户直接重试。
if (cachedFile === file) cachedURI = undefined;
throw error;
});
}
return cachedURI;
}
/** 清空已上传地址,确保新选择的文件不会错误复用旧头像。 */
function reset() {
cachedFile = undefined;
cachedURI = undefined;
}
return { resolve, reset };
}