smartstate/ts/smartstate.classes.smartstate.ts

49 lines
1.6 KiB
TypeScript
Raw Normal View History

2019-02-21 20:48:39 +00:00
import * as plugins from './smartstate.plugins';
import { StatePart } from './smartstate.classes.statepart';
/**
* Smartstate takes care of providing state
*/
export class Smartstate<StatePartNameType> {
2020-07-27 18:17:52 +00:00
public statePartMap: { [key: string]: StatePart<StatePartNameType, unknown> } = {};
2019-02-21 20:48:39 +00:00
constructor() {}
2019-09-25 13:28:39 +00:00
public getStatePart<PayloadType>(
2020-07-27 18:17:52 +00:00
statePartNameArg: string & StatePartNameType,
2020-11-29 23:31:31 +00:00
initialArg?: PayloadType,
initMode?: 'soft' | 'mandatory'
2019-02-21 20:48:39 +00:00
): StatePart<StatePartNameType, PayloadType> {
if (this.statePartMap[statePartNameArg as any]) {
2020-11-29 23:31:31 +00:00
if (initialArg && (!initMode || initMode !== 'soft')) {
2019-02-21 20:48:39 +00:00
throw new Error(
`${statePartNameArg} already exists, yet you try to set an initial state again`
);
}
2020-07-27 18:17:52 +00:00
return this.statePartMap[statePartNameArg] as StatePart<StatePartNameType, PayloadType>;
2019-02-21 20:48:39 +00:00
} else {
if (!initialArg) {
throw new Error(
`${statePartNameArg} does not yet exist, yet you don't provide an initial state`
);
}
return this.createStatePart<PayloadType>(statePartNameArg, initialArg);
}
}
2019-04-30 08:17:29 +00:00
/**
* creates a statepart
* @param statePartName
2019-09-25 13:28:39 +00:00
* @param initialPayloadArg
2019-04-30 08:17:29 +00:00
*/
2019-02-21 20:48:39 +00:00
private createStatePart<PayloadType>(
statePartName: StatePartNameType,
initialPayloadArg: PayloadType
): StatePart<StatePartNameType, PayloadType> {
const newState = new StatePart<StatePartNameType, PayloadType>(statePartName);
newState.setState(initialPayloadArg);
this.statePartMap[statePartName as any] = newState;
return newState;
}
}