#How to get an Enity's properties in a list
19 messages · Page 1 of 1 (latest)
Do you want it as a type, or as a variable you can reference?
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.
You can't. Typescript (javascript) does not have a capability to list non-method properties of a class. CGPT is wrong here.
smh
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
ah
I got a response that has something todo with that from ChatGPT when I prompted that does not work sadly
This should list all metadata available on the class: Reflect.getOwnMetadataKeys(Order).forEach((k) => console.log(k, Reflect.getMetadata(k, Order)))
It also depends on how the metadata is set..I believe Typeorm and class-validator/class-transformer use their own metadata storage engine
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 😦
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;
}
Reflect is from the ttypescript Reflect API. You can read more about it from the npm package reflect-metadata
ok