Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a helper method to a typeORM entity?

I'm trying to add a helper method to one of my Entity classes but I'm getting an error message. My entity:

import { Entity, PrimaryColumn, Column } from 'typeorm'

@Entity('accounts')
class Account {
  @PrimaryColumn()
  username: string

  @Column({ name: 'firstname' })
  firstName: string

  @Column({ name: 'lastname' })
  lastName: string

  public fullName() : string {
    return `${this.firstName} ${this.lastName}`
  }
}

When I try to call account.fullName() I get the following error message:

"account.fullName" is not a function

What am I getting wrong?

like image 238
Bonifacio2 Avatar asked May 27 '20 18:05

Bonifacio2


1 Answers

Add the get keyword and call it using property syntax.

import { Entity, PrimaryColumn, Column } from 'typeorm'

@Entity('accounts')
class Account {
  @PrimaryColumn()
  username: string

  @Column({ name: 'firstname' })
  firstName: string

  @Column({ name: 'lastname' })
  lastName: string

  public get fullName() : string {
    return `${this.firstName} ${this.lastName}`
  }
}
like image 121
drdgvhbh Avatar answered Sep 22 '22 18:09

drdgvhbh