smartstate/ts/smartstate.classes.smartstate.ts

73 lines
2.3 KiB
TypeScript
Raw Permalink Normal View History

2022-03-25 12:31:21 +00:00
import * as plugins from './smartstate.plugins.js';
import { StatePart } from './smartstate.classes.statepart.js';
2020-11-29 23:51:05 +00:00
2023-10-03 11:19:38 +00:00
export type TInitMode = 'soft' | 'mandatory' | 'force' | 'persistent';
2020-11-29 23:51:05 +00:00
/**
* Smartstate takes care of providing state
*/
export class Smartstate<StatePartNameType extends string> {
public statePartMap: { [key in StatePartNameType]?: StatePart<StatePartNameType, any> } = {};
2020-11-29 23:51:05 +00:00
constructor() {}
/**
* Allows getting and initializing a new statepart
* initMode === 'soft' it will allow existing stateparts
* initMode === 'mandatory' will fail if there is an existing statepart
2020-11-29 23:51:05 +00:00
* initMode === 'force' will overwrite any existing statepart
* @param statePartNameArg
* @param initialArg
* @param initMode
*/
2023-10-03 14:20:34 +00:00
public async getStatePart<PayloadType>(
statePartNameArg: StatePartNameType,
2020-11-29 23:51:05 +00:00
initialArg?: PayloadType,
2023-10-03 11:19:38 +00:00
initMode?: TInitMode
2023-10-03 14:20:34 +00:00
): Promise<StatePart<StatePartNameType, PayloadType>> {
if (this.statePartMap[statePartNameArg]) {
2020-11-29 23:51:05 +00:00
if (initialArg && (!initMode || initMode !== 'soft')) {
throw new Error(
`${statePartNameArg} already exists, yet you try to set an initial state again`
);
}
return this.statePartMap[statePartNameArg] as StatePart<StatePartNameType, PayloadType>;
} else {
if (!initialArg) {
throw new Error(
`${statePartNameArg} does not yet exist, yet you don't provide an initial state`
);
}
2023-10-03 11:19:38 +00:00
return this.createStatePart<PayloadType>(statePartNameArg, initialArg, initMode);
2020-11-29 23:51:05 +00:00
}
}
/**
* Creates a statepart
2020-11-29 23:51:05 +00:00
* @param statePartName
* @param initialPayloadArg
*/
2023-10-03 14:20:34 +00:00
private async createStatePart<PayloadType>(
2020-11-29 23:51:05 +00:00
statePartName: StatePartNameType,
2023-10-03 11:19:38 +00:00
initialPayloadArg: PayloadType,
initMode?: TInitMode
2023-10-03 14:20:34 +00:00
): Promise<StatePart<StatePartNameType, PayloadType>> {
2023-10-03 11:19:38 +00:00
const newState = new StatePart<StatePartNameType, PayloadType>(
statePartName,
initMode === 'persistent'
? {
dbName: 'smartstate',
storeName: statePartName,
}
: null
2023-10-03 11:19:38 +00:00
);
2023-10-03 17:19:54 +00:00
await newState.init();
2023-10-03 14:20:34 +00:00
const currentState = newState.getState();
await newState.setState({
...initialPayloadArg,
...currentState,
});
this.statePartMap[statePartName] = newState;
2020-11-29 23:51:05 +00:00
return newState;
}
}