52 lines
1.7 KiB
TypeScript
52 lines
1.7 KiB
TypeScript
import { parseAppError } from '../i18n'
|
|
|
|
export type VMSettingState<T> = { value: T | null; error: string; busy: boolean }
|
|
|
|
export function createVMSettingRequests<T>(activeVM: () => string, update: (patch: Partial<VMSettingState<T>>) => void) {
|
|
const writes = new Set<string>()
|
|
const revisions = new Map<string, number>()
|
|
|
|
return {
|
|
isWriting: (name: string) => writes.has(name),
|
|
watch(name: string, read: () => Promise<T>) {
|
|
let active = true
|
|
let pending = false
|
|
return {
|
|
async refresh() {
|
|
if (!active || pending || writes.has(name)) return
|
|
const revision = revisions.get(name)
|
|
const current = () => active && activeVM() === name && revision === revisions.get(name)
|
|
pending = true
|
|
try {
|
|
const value = await read()
|
|
if (current()) update({ value, error: '' })
|
|
} catch (error) {
|
|
if (current()) update({ error: parseAppError(error).summary })
|
|
} finally {
|
|
pending = false
|
|
}
|
|
},
|
|
stop() { active = false },
|
|
}
|
|
},
|
|
async write(name: string, save: () => Promise<T>): Promise<boolean> {
|
|
if (writes.has(name)) return false
|
|
revisions.set(name, (revisions.get(name) ?? 0) + 1)
|
|
writes.add(name)
|
|
update({ busy: true, error: '' })
|
|
try {
|
|
const value = await save()
|
|
if (activeVM() !== name) return false
|
|
update({ value })
|
|
return true
|
|
} catch (error) {
|
|
if (activeVM() === name) update({ error: parseAppError(error).summary })
|
|
return false
|
|
} finally {
|
|
writes.delete(name)
|
|
if (activeVM() === name) update({ busy: false })
|
|
}
|
|
},
|
|
}
|
|
}
|