add service state machine

FrozenArcher 2024-03-12 15:08:44 +08:00
parent 0120da0760
commit 55c286ac4b
1 changed files with 59 additions and 0 deletions

View File

@ -1,5 +1,8 @@
import process from 'process'; import process from 'process';
/**
* @deprecated use `ServiceState` instead
*/
export class RequestState { export class RequestState {
loading: boolean; loading: boolean;
success: boolean; success: boolean;
@ -9,6 +12,62 @@ export class RequestState {
} }
} }
/**
* Service state machine
*
* @example
* let former = that.state.service;
* that.setState({
* service: former.trans(true),
* })
*
*/
export class ServiceState {
private state: 'loading' | 'success' | 'failed';
constructor() {
this.state = 'loading';
}
/**
* Transist from `loading` to `success` or `failed`
* @param success request succeeded or not
*/
trans(success: boolean) {
if (this.state == 'loading') {
if (success) {
this.state = 'success';
} else {
this.state = 'failed';
}
}
}
/**
* Check if state is `loading`.
* @returns in `loading` state or not.
*/
isLoading(): boolean {
return this.state == 'loading';
}
/**
* Check if state is `success`.
* @returns in `success state or not.
*/
isSuccess(): boolean {
return this.state == 'success';
}
/**
* Check if state is `failed`.
* @returns in `failed` state or not.
*/
isFailed(): boolean {
return this.state == 'failed';
}
}
/** /**
* Get URL of backend * Get URL of backend
* @param path Relative path to base url, begins with `/` * @param path Relative path to base url, begins with `/`