add upload permission

This commit is contained in:
Timi
2026-01-29 11:58:18 +08:00
parent 81cb0b361d
commit 6e01e927b1
14 changed files with 213 additions and 36 deletions

View File

@ -0,0 +1,61 @@
import { JournalApi } from "../api/JournalApi";
const UPLOAD_PERMISSION_KEY = "journal:can-upload";
let cachedCanUpload: boolean | null = null;
let pendingCheck: Promise<boolean> | null = null;
function parseCachedValue(value: unknown): boolean | null {
if (value === true || value === false) {
return value;
}
if (value === "true") {
return true;
}
if (value === "false") {
return false;
}
return null;
}
export default class Permission {
/** 获取缓存的上传权限(不存在则返回 null */
static getCachedUploadPermission(): boolean | null {
if (cachedCanUpload !== null) {
return cachedCanUpload;
}
try {
const value = wx.getStorageSync(UPLOAD_PERMISSION_KEY);
const parsed = parseCachedValue(value);
if (parsed !== null) {
cachedCanUpload = parsed;
return parsed;
}
} catch (error) {
console.warn("读取上传权限缓存失败", error);
}
return null;
}
/** 检查并缓存上传权限 */
static async checkAndCacheUploadPermission(): Promise<boolean> {
if (pendingCheck) {
return await pendingCheck;
}
pendingCheck = (async () => {
try {
const canUpload = await JournalApi.canUpload();
cachedCanUpload = !!canUpload;
wx.setStorageSync(UPLOAD_PERMISSION_KEY, cachedCanUpload);
return cachedCanUpload;
} catch (error) {
console.error("检查上传权限失败", error);
const cached = this.getCachedUploadPermission();
const fallback = cached !== null ? cached : false;
return fallback;
} finally {
pendingCheck = null;
}
})();
return await pendingCheck;
}
}