簡體   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