#How to get an Enity's properties in a list

19 messages · Page 1 of 1 (latest)

crisp fern
#

Say I have an entity type like this ```ts
export class Order {
@ApiProperty()
DocEntry: number;

@ApiProperty()
CardCode: string;

@ApiProperty()
DocDate: string;
}```

From this, I want to get all of it's properties and store them in a list like so ['DocEntry', 'CardCode', 'DocDate']

How do I achieve this??

torpid flax
#

Do you want it as a type, or as a variable you can reference?

crisp fern
#

a variable

#
import { plainToClass } from 'class-transformer';
import { validateSync } from 'class-validator';

export function getPropertyNames(entityClass: any): string[] {
  const entityInstance: object = plainToClass(entityClass, {});
  const errors = validateSync(entityInstance);
  const propertyNames = Object.keys(entityInstance);

  // Remove properties with validation errors
  errors.forEach((error) => {
    const property = error.property;
    const index = propertyNames.indexOf(property);
    if (index !== -1) {
      propertyNames.splice(index, 1);
    }
  });

  return propertyNames;
}

Chat-gpt got me this function

#

but it doesnt work

      const propertyNames = getPropertyNames(Order);
      console.log(propertyNames); // []```
propertyNames is just empty.
lone gale
#

You can't. Typescript (javascript) does not have a capability to list non-method properties of a class. CGPT is wrong here.

crisp fern
#

smh

lone gale
#

However, Nest goes around it by using decorators which allow storing metadata on the class itself. You can try using Reflect to read the medstada off the class, you can probably extract something from there

crisp fern
#

ah

#

I got a response that has something todo with that from ChatGPT when I prompted that does not work sadly

lone gale
#

This should list all metadata available on the class: Reflect.getOwnMetadataKeys(Order).forEach((k) => console.log(k, Reflect.getMetadata(k, Order)))

torpid flax
#

It also depends on how the metadata is set..I believe Typeorm and class-validator/class-transformer use their own metadata storage engine

lone gale
#

Yeah, that's also true. I was sad to discover that nestjs/graphql also does not use Reflect, so you can't easily read the metadata off of a query handler 😦

crisp fern
#

I fail to run the console log

#

nothing logs

#

what is Reflect?

#

GPT tells me this ```ts
function getPropertyNames(entityClass: any): string[] {
const propertyNames = Object.getOwnPropertyNames(entityClass.prototype)
.filter((propertyName) => {
const metadata = Reflect.getMetadata('includedProperty', entityClass.prototype, propertyName);
return metadata === true;
});
return propertyNames;
}

torpid flax
#

Reflect is from the ttypescript Reflect API. You can read more about it from the npm package reflect-metadata

crisp fern
#

ok