get List of reflect-metadata decorated fields of class
Asked Answered
S

1

6

I'm using reflect-metadata with typescript. I composed my own property decorator and it's called Field. How to get list of fields/properties, which are decorated by Field, of any type. For example: I want to get ProductID, ProductName field with their metadata from class Product/shown in below/.

import 'reflect-metadata';

export const FIELD_METADATA_KEY = 'Field';

export interface FieldDecorator {
  field?: string;
  title?: string;
  type?: string;
}

export function Field(field: FieldDecorator) {
  return Reflect.metadata(FIELD_METADATA_KEY, field);
}


export class Product {
  @Field({
    title: 'Product Id'
  })
  ProductID: string;

  @Field({
    title: 'Product Name',
    type: 'text'
  })
  ProductName: string;

  UnitPrice: number; //not decorated
}
Silesia answered 19/6, 2017 at 10:16 Comment(0)
C
0

Unfortunately the reflect-metadata api does not expose this.

As a workaround you can store the list of fields yourself:


export const FIELD_METADATA_KEY = 'Field';
export const FIELD_LIST_METADATA_KEY = 'FieldList';

export function Field(field: FieldDecorator) {
  return (target: Object, propertyKey: string | symbol) => {
    // append propertyKey to field list metadata
    Reflect.defineMetadata(FIELD_LIST_METADATA_KEY, [...Reflect.getMetadata(FIELD_LIST_METADATA_KEY, target) ?? [], propertyKey], target);

    // your actual decorator
    Reflect.defineMetadata(FIELD_METADATA_KEY, field, target, propertyKey);
  };
}

// list of keys
Reflect.getMetadata(FIELD_LIST_METADATA_KEY, Product.prototype)

Cabdriver answered 28/10, 2021 at 10:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.