Named constructor with EntitySchema

I am trying to use TypeORM decoupled from my entitiy (User) definition so I am using EntitySchema. I have made my constructor private to enforce the use of named constructor, but when I try to retrieve an User it is not retrieving an instance of User but a plain object (with the user’s properties, tho).

Find below my entity definition and my entity schema definition

export const UserSchema = new EntitySchema<User>({
  name: 'users',
  columns: {
    id: {
      primary: true,
      type: String,
      transformer: ValueObjectTransformer(UserId),
    },
    name: {
      type: String,
      transformer: ValueObjectTransformer(UserName),
    },
    mail: {
      type: String,
      transformer: ValueObjectTransformer(UserEmail),
    },
    status: {
      type: Boolean,
      transformer: ValueObjectTransformer(UserStatus),
    },
  },
});
export default class User extends AggregateRoot {
  readonly #id: UserId;
  #name: UserName;
  #mail: UserEmail;
  #status: UserStatus;

  private constructor(
    id: UserId,
    name: UserName,
    mail: UserEmail,
    status: UserStatus,
  ) {
    super();
    this.#id = id;
    this.#name = name;
    this.#mail = mail;
    this.#status = status;
  }

  public static create(
    id: string,
    name: string,
    mail: string,
    status: boolean,
  ) {
    const userId = new UserId(id);
    const userName = new UserName(name);
    const userMail = new UserEmail(mail);
    const userStatus = new UserStatus(status);

    return new User(userId, userName, userMail, userStatus);
  }

  get id() {
    return this.#id;
  }

  get name() {
    return this.#name;
  }

  get mail() {
    return this.#mail;
  }

  get status() {
    return this.#status;
  }
}

I have tried to set target property of the EntitySchemaOptions to User.create, but it throws me a TypeError (the target is not a constructor):

TypeError: this.target is not a constructor
    at EntityMetadata.create (/metadata/EntityMetadata.ts:563:23)
    at EntityMetadataValidator.validate (/metadata-builder/EntityMetadataValidator.ts:211:47)

Any clue of how can I get this working? I don’t even know if something similar is possible with TypeORM but seems a pretty useful feature for me.

Thank you in advance!

  • Where is the code for EntityMetadata?

    – 

Leave a Comment