简体   繁体   English

基于另一个没有装饰器的域级 class 创建 TypeORM 实体

[英]Creating a TypeORM entity based on another domain-level class without decorators

I would like to separate between domain-level, pure business logic entities - and the TypeORM / any other framework bindings.我想将域级别的纯业务逻辑实体与 TypeORM / 任何其他框架绑定分开。

For example, right now an Address looks like this in order to bind it with TypeORM:例如,现在一个 Address 看起来像这样,以便将它与 TypeORM 绑定:

@Entity()
export class Address {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ nullable: true })
  firstName: string;

  @Column({ nullable: true })
  lastName: string;

  @Column({ nullable: true })
  streetAddress1: string;
}

I would rather have a pure data class such as我宁愿有一个纯数据 class 例如

export class Address {
  id: number;
  firstName: string;
  lastName: string;
  streetAddress1: string;
}

And define the TypeORM binding from another place, to separate concerns and not have my core business logic know anything about TypeORM (Or any other framework I might migrate to).并从另一个地方定义 TypeORM 绑定,以分离关注点,并且让我的核心业务逻辑不了解关于 TypeORM(或我可能迁移到的任何其他框架)的任何信息。

How would you approach this in a clean way, without creating a duplicate entity class just for TypeORM?您将如何以干净的方式处理此问题,而无需仅为 TypeORM 创建重复的实体 class? Any clever way to use the TypeScript type system to extend the existing pure entity class and decorate it for TypeORM DB binding?有什么聪明的方法可以使用 TypeScript 类型系统来扩展现有的纯实体 class 并为 TypeORM DB 绑定进行装饰?

One option might be to create a type from your TypeORM model, I've renamed it AddressEntity :一种选择可能是从您的 TypeORM model 创建一个类型,我已将其重命名为AddressEntity

@Entity()
export class AddressEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ nullable: true })
  firstName: string;

  @Column({ nullable: true })
  lastName: string;

  @Column({ nullable: true })
  streetAddress1: string;
}

...

type Address = typeof AddressEntity

const address: Address = {
   // ... typescript requires that you define these fields
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM