简体   繁体   中英

Access class decorator argument using reflect-metadata

Consider a class decorator with one argument:

@TableName("Orders")
export class Order {
 // ...
}

And the decorator defined as:

import "reflect-metadata";

const classDecoratorKey = Symbol.for("custom:TableName");

export function TableName(tableName: string): ClassDecorator {
  return (constructor: Function) => {
    Reflect.defineMetadata(classDecoratorKey, tableName, constructor);
  }
}

export function getTableName(target: any): string {
  return Reflect.getMetadata(classDecoratorKey, target.constructor, "class") || "";
}

I expect now to get the @TableName value "Orders". How can I retrieve the class decorator's argument value?

let order = new Order();
getTableName(order); // "" but expected "Orders"

Here's what worked for me

export function TableName(tableName: string): ClassDecorator {
  return (constructor: Function) => {
    Reflect.defineMetadata(classDecoratorKey, tableName, constructor.prototype);
  };
}

export function getTableName(target: any): string {
  return Reflect.getMetadata(classDecoratorKey, target) || '';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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