class-transformer: throw if source object doesn't fit destination class

378 Views Asked by At

I'm trying to handle different types of plainToInstance conversions using class-validator. I'd like to dynamically transform all responses based on the structure: if KikGenericResponse matches, then try to transform the "data" property inside. Otherwise just transform KikGenericResponse. The problem is that plainToInstance doesn't throw, but even passing a string it returns an empty instance of the class. Is there a way of preventing this behaviour? Maybe using class-validator before trying the parsing??

Thanks in advance

export class KikResponseMessage {
  @Expose()
  get subtitle(): string {
    return this._subtitle;
  }

  @Expose()
  get title(): string {
    return this._title;
  }

  @Expose()
  get type(): string {
    return this._type;
  }

  constructor(
    private _title: string,
    private _subtitle?: string,
    private _type: KikResponseMessageTypes = KikResponseMessageTypes.ERROR
  ) {}
}
export class KikGenericResponse<T = any> {
  set messages(newValue: KikResponseMessage[]) {
    this._messages = newValue;
  }

  @Transform(({ value }) => (value.length ? value : void 0))
  get messages(): KikResponseMessage[] {
    return this._messages;
  }

  constructor(
    public data?: T,
    protected _messages: KikResponseMessage[] = []
  ) {}
}

 private _foo: any = instanceToPlain(new KikFoo());
  private _message: KikResponseMessage = new KikResponseMessage('Attenzione');
  private _plainResponse: any = {
    data: {
      foo: 1,
    },
    messages: [instanceToPlain(this._message)],
  };

  constructor(){
      this._testClassTransformer();
  }

  private _testClassTransformer(): void {
    console.info('PLAIN', this._plainResponse);
    const parsed = plainToInstance(KikGenericResponse, this._plainResponse);
    console.info('PARSED GENERIC RESP', {
      whole: parsed,
      msgs: parsed.messages,
    });
    const parsedError = plainToInstance(KikGenericResponse, "this._foo", {
      enableImplicitConversion: !0,
      excludeExtraneousValues: !0
    });
    console.info('Foo to KikGenericResponse (expecting error)', parsedError);
  }
0

There are 0 best solutions below