|
| 1 | +import type { |
| 2 | + StackflowActions, |
| 3 | + StackflowPlugin, |
| 4 | +} from "@stackflow/core"; |
| 5 | +import { StackSnapshotRecordSaveError, StackSnapshotRecordLoadError } from "./errors"; |
| 6 | +import type { StackSnapshotStorage } from "./StackSnapshotStorage"; |
| 7 | +import type { StackSnapshotStrategy } from "./StackSnapshotStrategy"; |
| 8 | + |
| 9 | +export type StackPersistencePluginOptions<Metadata> = { |
| 10 | + storage: StackSnapshotStorage<Metadata>; |
| 11 | + strategy: StackSnapshotStrategy<Metadata>; |
| 12 | + onRecordLoadError?: (error: StackSnapshotRecordLoadError) => void; |
| 13 | + onRecordSaveError?: (error: StackSnapshotRecordSaveError) => void; |
| 14 | + onLoadError?: NonNullable<ReturnType<StackflowPlugin>['onLoadError']>; |
| 15 | +} |
| 16 | + |
| 17 | +export function stackPersistencePlugin<Metadata>( |
| 18 | + { storage, strategy, onRecordLoadError, onRecordSaveError, onLoadError }: StackPersistencePluginOptions<Metadata>, |
| 19 | +): StackflowPlugin { |
| 20 | + return () => { |
| 21 | + const saveIfIdle = (actions: StackflowActions) => { |
| 22 | + const stack = actions.getStack(); |
| 23 | + |
| 24 | + if (stack.globalTransitionState !== "idle") return; |
| 25 | + |
| 26 | + const snapshot = actions.captureSnapshot(); |
| 27 | + const metadata = strategy.createMetadata({ snapshot }); |
| 28 | + |
| 29 | + storage.save({ |
| 30 | + snapshot, |
| 31 | + metadata |
| 32 | + }).catch(error => { |
| 33 | + if (onRecordSaveError) return onRecordSaveError(error); |
| 34 | + else throw error; |
| 35 | + }); |
| 36 | + } |
| 37 | + |
| 38 | + return { |
| 39 | + key: "@stackflow/plugin-stack-persistence", |
| 40 | + provideSnapshot({ initialContext }) { |
| 41 | + try { |
| 42 | + const record = storage.load(); |
| 43 | + |
| 44 | + if (!record) |
| 45 | + return null; |
| 46 | + if (strategy?.shouldReuse({ record, initialContext }) === false) |
| 47 | + return null; |
| 48 | + |
| 49 | + return record.snapshot; |
| 50 | + } catch (error) { |
| 51 | + onRecordLoadError?.(new StackSnapshotRecordLoadError(error)); |
| 52 | + |
| 53 | + return null; |
| 54 | + } |
| 55 | + }, |
| 56 | + onLoadError(...args) { |
| 57 | + return onLoadError?.(...args) ?? { policy: "recover" } |
| 58 | + }, |
| 59 | + onInit({ actions }) { |
| 60 | + saveIfIdle(actions); |
| 61 | + }, |
| 62 | + onChanged({ actions }) { |
| 63 | + saveIfIdle(actions); |
| 64 | + }, |
| 65 | + }; |
| 66 | + }; |
| 67 | +} |
0 commit comments