Created
January 26, 2018 17:55
-
-
Save baetheus/c531e50fc8003c638869156e303b607c to your computer and use it in GitHub Desktop.
Pat's Action Factory
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
| export enum ActionState { | |
| INIT = "[ActionState] INIT", | |
| OK = "[ActionState] OK", | |
| ERROR = "[ActionState] ERROR", | |
| } | |
| export interface BaseAction <G, A extends ActionState, P = void> { | |
| readonly group: G; | |
| readonly state: A; | |
| readonly payload?: P; | |
| } | |
| export interface InitAction <G, P, OK = void, ERROR = void> extends BaseAction <G, ActionState.INIT, P> { | |
| ok(payload?: Partial<OK>): OkAction<G, OK>; | |
| error(payload?: Partial<ERROR>): ErrorAction<G ,ERROR>; | |
| } | |
| export interface OkAction <G, P> extends BaseAction <G, ActionState.OK, P> { | |
| } | |
| export interface ErrorAction <G, ERROR> extends BaseAction <G, ActionState.ERROR, ERROR> { | |
| } | |
| export const actionFactory = <G, P, OK = void, ERROR = void> ( | |
| group: G, | |
| payload: P, | |
| ok?: OK, | |
| error?: ERROR, | |
| ) => ({ | |
| group, | |
| state: ActionState.INIT, | |
| payload, | |
| ok: (payload?: Partial<OK>) => ( | |
| { group, state: ActionState.OK, payload: Object.assign(ok, payload) } | |
| ), | |
| error: (payload?: Partial<ERROR>) => ( | |
| { group, state: ActionState.ERROR, payload: Object.assign(error, payload) } | |
| ), | |
| }); | |
| enum Group { | |
| LOAD_THING = 'LOAD_THING', | |
| } | |
| const action = actionFactory(Group.LOAD_THING, 1, "string"); | |
| const ok = action.ok(); | |
| const err = action.error(); | |
| type Actions = typeof action | typeof action.ok | typeof action.error; | |
| function go (action: Actions) { | |
| switch (action.group) { | |
| case Group.LOAD_THING: | |
| switch (action.state) { | |
| case ActionState.INIT: | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment