You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lib/src/util/support/Rehydratable.ts

45 lines
1.1 KiB

/**
* Type representing a JSON serializable object.
*/
import {ErrorWithContext} from '../error/ErrorWithContext'
import {Awaitable} from './types'
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
*/
export function isJSONState(what: unknown): what is JSONState {
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>
*/
dehydrate(): Awaitable<JSONState>
/**
* Rehydrate a state into this class.
* @param {JSONState} state
* @return void|Promise<void>
*/
rehydrate(state: JSONState): Awaitable<void>
}