Skip to content

Instantly share code, notes, and snippets.

@baetheus
Created April 13, 2020 22:47
Show Gist options
  • Select an option

  • Save baetheus/3c693b339f1a408f8e67175747856064 to your computer and use it in GitHub Desktop.

Select an option

Save baetheus/3c693b339f1a408f8e67175747856064 to your computer and use it in GitHub Desktop.
Angular helpers for @nll/dux test
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