Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ERROR [ExceptionsHandler] You need to use @UseDto on class (ClassNameEntity) be able to call toDto function #332

Open
tinnt-uranus opened this issue Sep 24, 2023 · 2 comments

Comments

@tinnt-uranus
Copy link

tinnt-uranus commented Sep 24, 2023

// use-dto.decorator.ts

import { type Constructor } from '../types';

export function UseDto(dtoClass: Constructor): ClassDecorator {
  return (ctor) => {
    // FIXME make dtoClass function returning dto

    if (!(<unknown>dtoClass)) {
      throw new Error('UseDto decorator requires dtoClass');
    }

    // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
    ctor.prototype.dtoClass = dtoClass;
  };
}

The ctor.prototype.dtoClass always undefined.

@KoudouMax
Copy link

use Reflect metadata.
// use-dto-decorator.ts
export const DTO_KEY = Symbol('DTO_KEY');

export function UseDto(dto: Constructor): ClassDecorator {
// eslint-disable-next-line @typescript-eslint/ban-types
return (target: Function) => {
Reflect.defineMetadata(DTO_KEY, dto, target);
};
}

//abtract.entity.ts
toDto(options?: O): DTO {
const DtoClass = Reflect.getMetadata(DTO_KEY, this.constructor);

if (!DtoClass) {
  throw new Error(
    `You need to use @UseDto on class (${this.constructor.name}) be able to call toDto function`,
  );
}

return new DtoClass(this, options);

}

@tuancao-mti
Copy link

tuancao-mti commented Oct 13, 2023

Actual, we don't need to define private dtoClass?: Constructor<DTO, [AbstractEntity, O?]>; in abstract.entity.ts. Just remove it and make a change in toDto method.

toDto(options?: O): DTO
{

const dtoClass = Object.getPrototypeOf(this).dtoClass;

if (!dtoClass) {
  throw new Error(
    `You need to use @UseDto on class (${this.constructor.name}) be able to call toDto function`,
  );
}

return new dtoClass(this, options);

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants