15 lines
1.5 KiB
TypeScript
15 lines
1.5 KiB
TypeScript
import { newRequestId } from './api'
|
|
export interface PendingSubmission { key:string; operation:string; path:string; body:string; created_at:string }
|
|
let owner = ''
|
|
export function setStorageOwner(id:string) { owner=id }
|
|
function storageKey(){if(!owner)throw new Error('请先登录');return `cmvr:v2:outbox:${owner}`}
|
|
export function pendingSubmissions():PendingSubmission[]{try{return JSON.parse(localStorage.getItem(storageKey())||'[]')}catch{return []}}
|
|
function save(items:PendingSubmission[]){localStorage.setItem(storageKey(),JSON.stringify(items))}
|
|
export async function durableRequest<T>(operation:string,path:string,body:unknown,send:(path:string,key:string,body:string)=>Promise<T>):Promise<T>{
|
|
const serialized=JSON.stringify(body), storage=storageKey()
|
|
let items=pendingSubmissions(), entry=items.find(x=>x.operation===operation&&x.path===path&&x.body===serialized)
|
|
if(!entry){entry={key:newRequestId(),operation,path,body:serialized,created_at:new Date().toISOString()};items.push(entry);save(items)}
|
|
try{const result=await send(entry.path,entry.key,entry.body);const current:PendingSubmission[]=JSON.parse(localStorage.getItem(storage)||'[]');localStorage.setItem(storage,JSON.stringify(current.filter(x=>x.key!==entry!.key)));return result}
|
|
catch(error){const status=(error as {status?:number}).status;if(status&&status>=400&&status<500&&status!==409&&status!==401&&status!==403){const current:PendingSubmission[]=JSON.parse(localStorage.getItem(storage)||'[]');localStorage.setItem(storage,JSON.stringify(current.filter(x=>x.key!==entry!.key)))}throw error}
|
|
}
|