HexaCrop
HexaCrop

Reputation: 4293

get instance fields from a TypeORM entity class

I have an typeorm entity of the following form:

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    firstName: string;

    @Column()
    lastName: string;

    @Column()
    isActive: boolean;
}

Now I am looking to get the instance fields from this entity class into an array, like below:

['id', 'firstName', 'lastName', 'isActive']

How can I achieve that?

I tried the following but with no help:

class Me extends User{
    constructor() {
        super()     
    }
}

const me = new Me()
console.log(Object.keys(me)) // []

Upvotes: 1

Views: 2274

Answers (2)

Audwin Oyong
Audwin Oyong

Reputation: 2531

You might be able to do something like this:

const userProps = getConnection()
  .getMetadata(User)
  .ownColumns
  .map(column => column.propertyName);

This means that you obtain metadata from an entity if you take the class function (AKA constructor) and use the .getMetadata method on the DB connection.

Reference:

Get all properties from a entity #1764

Upvotes: 1

Give initial values in your User class to the properties. They are null now, Object.keys wont list them. Try this:

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id: number = 0;

    @Column()
    firstName: string = "";

    @Column()
    lastName: string = "";

    @Column()
    isActive: boolean = false;
}

Alternative solution is when you fill the attrs manually:

const user = new User();
user.id = 0;
user.firstName = "";
user.lastName = "";
user.isActive = false;

Upvotes: 0

Related Questions