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

时间:2020-09-08 06:45:57

标签: javascript typescript typeorm

import { PrimaryColumn, Column } from 'typeorm';

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

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

在过去的几个小时中,我试图弄清楚如何从属性装饰器location_id中检索名称属性值area_code@Column(),但是没有运气。我不确定是否可以获得属性列表。

1 个答案:

答案 0 :(得分:2)

typeorm源代码(这里为1234)来看,您可以通过全局变量访问各种内容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. 将columns变量传递到overwrite属性中。

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