import {BaseSerializer} from '../../../support/bus' import {ObjectSerializer} from '../../../support/bus/serial/decorators' import {Injectable, Instantiable} from '../../../di' import {Awaitable, ErrorWithContext, JSONState} from '../../../util' import {MigrationEvent} from './MigrationEvent' import {Migrations} from '../../services/Migrations' import {AppliedMigrationEvent} from './AppliedMigrationEvent' import {ApplyingMigrationEvent} from './ApplyingMigrationEvent' import {RolledBackMigrationEvent} from './RolledBackMigrationEvent' import {RollingBackMigrationEvent} from './RollingBackMigrationEvent' export interface MigrationEventSerialPayload extends JSONState { identifier: string eventType: string } @ObjectSerializer() @Injectable() export class MigrationEventSerializer extends BaseSerializer { protected decodeSerial(serial: MigrationEventSerialPayload): Awaitable { const migration = this.make(Migrations).get(serial.identifier) if ( !migration ) { throw new ErrorWithContext(`Invalid serialized migration identifier: ${serial.identifier}`) } return (new (this.stringToEvent(serial.eventType))(migration)) } protected encodeActual(actual: MigrationEvent): Awaitable { return { identifier: actual.migration.identifier, eventType: actual.eventName, } } protected getName(): string { return '@extollo/lib.MigrationEventSerializer' } matchActual(some: MigrationEvent): boolean { return some instanceof MigrationEvent } private stringToEvent(name: string): Instantiable { if ( name === '@extollo/lib.AppliedMigrationEvent' ) { return AppliedMigrationEvent } else if ( name === '@extollo/lib.ApplyingMigrationEvent' ) { return ApplyingMigrationEvent } else if ( name === '@extollo/lib.RollingBackMigrationEvent' ) { return RollingBackMigrationEvent } else if ( name === '@extollo/lib.RolledBackMigrationEvent' ) { return RolledBackMigrationEvent } throw new ErrorWithContext(`Invalid migration event name: ${name}`, { name, }) } }