lib/src/util/support/Rehydratable.ts

45 lines
1.1 KiB
TypeScript
Raw Normal View History

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'
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.
* @return JSONState|Promise<JSONState>
2021-06-02 01:59:40 +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>
*/
rehydrate(state: JSONState): Awaitable<void>
2021-06-02 01:59:40 +00:00
}