返回 AiToEarn
usePluginPublishCache.ts
根目录 / project / aitoearn-web / src / components / Chat / ChatMessage / PluginPublishCard / usePluginPublishCache.ts
1 /**
2 * usePluginPublishCache - 插件发布状态持久化缓存
3 * 功能:缓存发布成功状态,刷新页面后恢复已发布卡片的状态
4 */
5
6 import type { IActionCard } from '@/store/agent/agent.types'
7 import { createPersistStore } from '@/utils/storage/createPersistStore'
8
9 export interface PluginPublishRecord {
10 state: 'SUCCESS' | 'ERROR'
11 shareLink?: string
12 errorMsg?: string
13 timestamp: number
14 }
15
16 interface PluginPublishCacheState {
17 records: Record<string, PluginPublishRecord>
18 }
19
20 /** 简单 hash 函数,将字符串转为短 hash */
21 function simpleHash(str: string): string {
22 let hash = 0
23 for (let i = 0; i < str.length; i++) {
24 const char = str.charCodeAt(i)
25 hash = ((hash << 5) - hash) + char
26 hash |= 0 // 转为 32 位整数
27 }
28 return Math.abs(hash).toString(36)
29 }
30
31 /** 从 action 属性生成稳定的缓存 key */
32 export function getActionKey(action: IActionCard): string {
33 const raw = `${action.platform || ''}-${action.accountId || ''}-${action.title || ''}-${action.description || ''}`
34 return `pp-${simpleHash(raw)}`
35 }
36
37 const initialState: PluginPublishCacheState = {
38 records: {},
39 }
40
41 /** 缓存过期时间:7 天 */
42 const EXPIRE_MS = 7 * 24 * 60 * 60 * 1000
43
44 export const usePluginPublishCache = createPersistStore(
45 { ...initialState },
46 (set, get) => ({
47 getRecord(key: string): PluginPublishRecord | null {
48 const record = get().records[key]
49 if (!record)
50 return null
51 // 过期清理
52 if (Date.now() - record.timestamp > EXPIRE_MS) {
53 const { [key]: _, ...rest } = get().records
54 set({ records: rest })
55 return null
56 }
57 return record
58 },
59
60 setRecord(key: string, data: PluginPublishRecord) {
61 set({
62 records: { ...get().records, [key]: data },
63 })
64 },
65 }),
66 { name: 'plugin-publish-cache' },
67 )
68
68 lines TYPESCRIPT