-
Notifications
You must be signed in to change notification settings - Fork 78
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 = <S = any>(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<S> = (path: any, ...segments: any) => { | ||
return (store as any).path(path, ...segments); | ||
}; | ||
return { | ||
get<U = any>(path: Path<S, U>): 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<U = any>(path: Path<S, U[]>, index: number) { | ||
return store.at(path, index); | ||
}, | ||
executor<T extends Process<any, any>>(process: T): ReturnType<T> { | ||
return process(store) as any; | ||
} | ||
}; | ||
}); | ||
return storeMiddleware; | ||
}; | ||
|
||
export default createStoreMiddleware(); |