2021-06-02 01:59:40 +00:00
|
|
|
/**
|
|
|
|
* Type representing a JSON serializable object.
|
|
|
|
*/
|
2021-06-03 03:36:25 +00:00
|
|
|
import {ErrorWithContext} from '../error/ErrorWithContext'
|
2021-07-03 02:44:34 +00:00
|
|
|
import {Awaitable} from './types'
|
2021-06-02 01:59:40 +00:00
|
|
|
|
|
|
|
export type JSONState = { [key: string]: string | boolean | number | undefined | JSONState | Array<string | boolean | number | undefined | JSONState> }
|
|
|
|
|
|
|
|
/**
|
|
|
|
* An error thrown when the state passed into a class is invalid for that class.
|
|
|
|
*/
|
|
|
|
export class InvalidJSONStateError extends ErrorWithContext {}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns true if the given object can be JSON serialized.
|
|
|
|
* @param what
|
|
|
|
* @return boolean
|
|
|
|
*/
|
2021-06-03 03:36:25 +00:00
|
|
|
export function isJSONState(what: unknown): what is JSONState {
|
2021-06-02 01:59:40 +00:00
|
|
|
try {
|
|
|
|
JSON.stringify(what)
|
|
|
|
return true
|
|
|
|
} catch (e) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Base interface for a class that can be rehydrated and restored.
|
|
|
|
*/
|
|
|
|
export interface Rehydratable {
|
|
|
|
/**
|
|
|
|
* Dehydrate this class' state and get it.
|
2021-07-03 02:44:34 +00:00
|
|
|
* @return JSONState|Promise<JSONState>
|
2021-06-02 01:59:40 +00:00
|
|
|
*/
|
2021-07-03 02:44:34 +00:00
|
|
|
dehydrate(): Awaitable<JSONState>
|
2021-06-02 01:59:40 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Rehydrate a state into this class.
|
|
|
|
* @param {JSONState} state
|
|
|
|
* @return void|Promise<void>
|
|
|
|
*/
|
2021-07-03 02:44:34 +00:00
|
|
|
rehydrate(state: JSONState): Awaitable<void>
|
2021-06-02 01:59:40 +00:00
|
|
|
}
|