Created
April 13, 2020 22:47
-
-
Save baetheus/3c693b339f1a408f8e67175747856064 to your computer and use it in GitHub Desktop.
Angular helpers for @nll/dux test
This file contains hidden or 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
| import { Store as S, createStore, MetaReducer, RunOnce, RunEvery } from "./Store"; | |
| import { Reducer } from "./Reducers"; | |
| export interface StoreConfig<T> { | |
| readonly reducers: Reducer<T>[]; | |
| readonly metaReducers: MetaReducer<T>[]; | |
| readonly runOnces: RunOnce<T>[]; | |
| readonly runEverys: RunEvery<T>[]; | |
| } | |
| const DEFAULT_STORE_CONFIG = <T>(): StoreConfig<T> => ({ | |
| reducers: [], | |
| metaReducers: [], | |
| runOnces: [], | |
| runEverys: [] | |
| }); | |
| export abstract class Store<T> { | |
| private store!: S<T>; | |
| readonly select!: S<T>["select"]; | |
| readonly dispatch!: S<T>["dispatch"]; | |
| readonly getState!: S<T>["getState"]; | |
| readonly setState!: S<T>["setState"]; | |
| constructor(initialState: T, config?: Partial<StoreConfig<T>>) { | |
| const _config: StoreConfig<T> = { ...DEFAULT_STORE_CONFIG(), ...config }; | |
| this.store = createStore(initialState) | |
| .addReducers(..._config.reducers) | |
| .addMetaReducers(..._config.metaReducers) | |
| .addRunOnces(..._config.runOnces) | |
| .addRunEverys(..._config.runEverys); | |
| this.select = this.store.select; | |
| this.dispatch = this.store.dispatch; | |
| this.getState = this.store.getState; | |
| this.setState = this.store.setState; | |
| } | |
| } | |
| /** | |
| * Usage | |
| */ | |
| type Count = { count: number }; | |
| // @Injectable() | |
| export class CountService extends Store<Count> { | |
| // Inject tokens needed to link up the CountService | |
| constructor() { | |
| super({ count: 0 }, { reducers: [] }); | |
| } | |
| } | |
| const a = new CountService(); | |
| a.setState({ count: 1 }); | |
| console.log(a.getState()); // { count: 1 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment