繁体   English   中英

如何从 TypeORM 属性装饰器获取值

[英]How can I get values from a TypeORM property decorator

import { PrimaryColumn, Column } from 'typeorm';

export class LocationStatus {
  @PrimaryColumn({ name: 'location_id' })
  locationId: string;

  @Column({ name: 'area_code', type: 'int' })
  areaCode: number;
}

我花了几个小时试图弄清楚如何从属性装饰器@Column()检索名称属性值location_idarea_code ,但没有运气。 我不确定是否有可能获得属性列表。

typeorm源代码(此处: 1 , 2 , 3 , 4 )来看,您可以通过全局变量typeormMetadataArgsStorage (如window.typeormMetadataArgsStorageglobal.typeormMetadataArgsStorage )访问各种内容。 探索它,我相信你会找到你想要的东西:

const global_context = ??? // depends on your environment
const property_to_look_for = `areaCode`
const name = global_context.typeormMetadataArgsStorage
  .columns
  .filter(col => col.propertyName === property_to_look_for && col.target === LocationStatus)
  .options
  .name
console.log(name)

更新

对于那些目前像我一样使用Nest ,这是我迄今为止所做的。


import { getMetadataArgsStorage, InsertResult } from 'typeorm';

export class PinLocationStatusRepository extends Repository<PinLocationStatus> {
  // Column names in this array, the value should not be modified.
  // For instance, the location_id value "location_ko_01" won't be changed.
  private static immutableColumnNames = ['location_id', ...]; 

  private static mutableColumnFound(name: string): boolean {
    return PinLocationStatusRepository.immutableColumnNames.every(colName => colName !== name);
  }

  savePinLocation(state: PinLocationStatus): Promise<InsertResult> {
    const columns = getMetadataArgsStorage()
     .columns.filter(({ target }) => target === PinLocationStatus)
     .map(({ options, propertyName }) => (!options.name ? propertyName : options.name))
     .reduce((columns, name) => {
       if (PinLocationStatusRepository.mutableColumnFound(name)) {
         columns.push(name);
       }
       return columns;
    }, []);

    return this.createQueryBuilder()
      .insert()
      .into(PinLocationStatus)
      .values(state)
      .orUpdate({ overwrite: columns }) // ['area_code']
      .execute();
  }
}
  1. @Column()装饰器中提取列名。
  2. 过滤掉一些值必须保持不变的列名。
  3. 将列变量传递给overwrite属性。

除非area_code是不可变列,否则您将获得正确的结果。

暂无
暂无

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

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