85 lines
2.4 KiB
TypeScript
85 lines
2.4 KiB
TypeScript
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<TActual, TSerial extends JSONState> {
|
|
|
|
/**
|
|
* 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<TActual, TSerial>): boolean {
|
|
return serial.serializer === this.getName()
|
|
}
|
|
|
|
/**
|
|
* Encode the payload as a JSON state.
|
|
* @param actual
|
|
* @protected
|
|
*/
|
|
protected abstract encodeActual(actual: TActual): Awaitable<TSerial>
|
|
|
|
/**
|
|
* Decode the payload back to the original object.
|
|
* @param serial
|
|
* @protected
|
|
*/
|
|
protected abstract decodeSerial(serial: TSerial): Awaitable<TActual>
|
|
|
|
/**
|
|
* 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<SerialPayload<TActual, TSerial>> {
|
|
return {
|
|
serializer: this.getName(),
|
|
payload: await this.encodeActual(actual),
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Decode a value from a serial payload.
|
|
* @param serial
|
|
*/
|
|
public async decode(serial: SerialPayload<TActual, TSerial>): Promise<TActual> {
|
|
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>(RequestLocalStorage)
|
|
.get()
|
|
}
|
|
|
|
/** Get a dependency from the container. */
|
|
protected make<T>(key: TypedDependencyKey<T>): T {
|
|
return Container.getContainer()
|
|
.make(key)
|
|
}
|
|
}
|