From 65f3a89c26b0b21f7adda19363a1115428c31991 Mon Sep 17 00:00:00 2001 From: Anthony Gubler Date: Fri, 7 Jun 2019 09:44:37 +0100 Subject: [PATCH] Store middleware --- src/core/middleware/store.ts | 45 ++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/core/middleware/store.ts diff --git a/src/core/middleware/store.ts b/src/core/middleware/store.ts new file mode 100644 index 000000000..56a5bb1fd --- /dev/null +++ b/src/core/middleware/store.ts @@ -0,0 +1,45 @@ +import { destroy, invalidator, create } from '../vdom'; +import Store, { StatePaths, Path } from '../../stores/Store'; +import { Process } from '../../stores/process'; + +const factory = create({ destroy, invalidator }); + +export const createStoreMiddleware = (initial?: Function) => { + let store = new Store(); + initial && initial(store); + const storeMiddleware = factory(({ middleware: { destroy, invalidator } }) => { + const handles: any[] = []; + destroy(() => { + let handle: any; + while ((handle = handles.pop())) { + handle(); + } + }); + const registeredPaths: string[] = []; + const path: StatePaths = (path: any, ...segments: any) => { + return (store as any).path(path, ...segments); + }; + return { + get(path: Path): U { + if (registeredPaths.indexOf(path.path) === -1) { + const handle = store.onChange(path, () => { + invalidator(); + }); + handles.push(() => handle.remove()); + registeredPaths.push(path.path); + } + return store.get(path); + }, + path, + at(path: Path, index: number) { + return store.at(path, index); + }, + executor>(process: T): ReturnType { + return process(store) as any; + } + }; + }); + return storeMiddleware; +}; + +export default createStoreMiddleware();