import {Awaitable, JSONState} from '../../../util' import {SerialPayload} from '../types' import {Serialization} from './Serialization' import {Container, TypedDependencyKey} from '../../../di' import {Request} from '../../../http/lifecycle/Request' import {RequestLocalStorage} from '../../../http/RequestLocalStorage' /** * A core Serializer implementation. */ export abstract class BaseSerializer { /** * Return true if the value can be encoded by this serializer. * @param some */ public abstract matchActual(some: TActual): boolean /** * Return true if the serial payload can be decoded by this serializer. * @param serial */ public matchSerial(serial: SerialPayload): boolean { return serial.serializer === this.getName() } /** * Encode the payload as a JSON state. * @param actual * @protected */ protected abstract encodeActual(actual: TActual): Awaitable /** * Decode the payload back to the original object. * @param serial * @protected */ protected abstract decodeSerial(serial: TSerial): Awaitable /** * Get the unique name of this serializer. * @protected */ protected abstract getName(): string /** * Encode a value to a serial payload. * @param actual */ public async encode(actual: TActual): Promise> { return { serializer: this.getName(), payload: await this.encodeActual(actual), } } /** * Decode a value from a serial payload. * @param serial */ public async decode(serial: SerialPayload): Promise { return this.decodeSerial(serial.payload) } /** Helper to get an instance of the Serialization service. */ protected getSerialization(): Serialization { return Container.getContainer() .make(Serialization) } /** Helper to get an instance of the global Request. */ protected getRequest(): Request { return Container.getContainer() .make(RequestLocalStorage) .get() } /** Get a dependency from the container. */ protected make(key: TypedDependencyKey): T { return Container.getContainer() .make(key) } }