59 lines
1.6 KiB
TypeScript
59 lines
1.6 KiB
TypeScript
import type { MeResponse } from '@/api/client'
|
|
import { captureSessionGeneration, isSessionCurrent } from '@/api/authSession'
|
|
import { StaleSessionError } from '@/api/errors'
|
|
|
|
type ApplyMe = (data: MeResponse) => boolean
|
|
|
|
let queueEpoch = 0
|
|
let queueTail: Promise<void> = Promise.resolve()
|
|
let applyMe: ApplyMe = () => false
|
|
|
|
export function bindMeMutationApply(fn: ApplyMe): void {
|
|
applyMe = fn
|
|
}
|
|
|
|
export function resetMeMutationQueue(): void {
|
|
queueEpoch += 1
|
|
queueTail = Promise.resolve()
|
|
}
|
|
|
|
export function resetMeMutationQueueForTests(): void {
|
|
resetMeMutationQueue()
|
|
}
|
|
|
|
function assertMutationSession(epochAtEnqueue: number, sessionGen: number): void {
|
|
if (epochAtEnqueue !== queueEpoch) {
|
|
throw new StaleSessionError()
|
|
}
|
|
if (!isSessionCurrent(sessionGen)) {
|
|
throw new StaleSessionError()
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Serializes state-changing API calls in this tab so a slower response cannot apply before
|
|
* a later mutation finishes. Does not replace server revision — see docs in sync.ts.
|
|
*/
|
|
export async function runMeMutation<R>(
|
|
fetcher: () => Promise<R>,
|
|
pickMe: (result: R) => MeResponse = (result) => result as unknown as MeResponse,
|
|
): Promise<R> {
|
|
const sessionGen = captureSessionGeneration()
|
|
const epochAtEnqueue = queueEpoch
|
|
|
|
const execute = async (): Promise<R> => {
|
|
assertMutationSession(epochAtEnqueue, sessionGen)
|
|
const result = await fetcher()
|
|
assertMutationSession(epochAtEnqueue, sessionGen)
|
|
applyMe(pickMe(result))
|
|
return result
|
|
}
|
|
|
|
const resultPromise = queueTail.then(execute)
|
|
queueTail = resultPromise.then(
|
|
() => undefined,
|
|
() => undefined,
|
|
)
|
|
return resultPromise
|
|
}
|