TypeORM: helper methods on entities using data mapper pattern

140 Views Asked by At

We're building a rather large application and opted to use TypeORM's data mapper pattern for maintenance purposes. We are using TypeORM version 0.2.45.

When I define a method on my entity classes, these seem to get lost when reading from the database.

Example entity

export class Person implements IPerson {
  firstName: string;
  lastName: string;

  getFullName(title: string): string {
    return `${title}. ${this.firstName} ${this.lastName}`;
  }
}

export interface IPerson {
  firstName: string;
  lastName: string;
}

Example schema

import { EntitySchema } from 'typeorm';

export const PersonSchema = new EntitySchema<IPerson>({
  name: Person.name,
  columns: {
    firstName: {
      type: 'text',
      nullable: false,
    },
    lastName: {
      type: 'text',
      nullable: false,
    },
  },
});

Example repository and usage

import { EntityRepository, Repository, getCustomRepository } from 'typeorm';

@EntityRepository(PersonSchema)
export class PersonRepository extends Repository<Person> {}

const personRepository = getCustomRepository(PersonRepository);

const person = await personRepository.findOne();
person.getFullName('Mr'); // Error, undefined is not a function

Obviously, if I just simply create a Person, the method exists:

const person = new Person();
person.firstName = 'John';
person.lastName = 'Doe';
person.getFullName('Mr'); // Returns 'Mr. John Doe'

So it seems when serializing results to classes, only the fields on the schema are properly set in the class and the methods are not. So my question is twofold:

  1. Is it possible to add custom methods to TypeORM entities?
  2. If so, how can I achieve this using the data mapper pattern?

Many thanks in advance!

0

There are 0 best solutions below