Files
gaoYuJournal/miniprogram/utils/Permission.ts
2026-01-29 11:58:18 +08:00

62 lines
1.6 KiB
TypeScript
Raw Permalink 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.

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;
}
}