From 161a3ab509ba811b82f10b1fe0818f548d4064a7 Mon Sep 17 00:00:00 2001 From: Etienne Bechara Date: Sun, 30 May 2021 22:22:52 -0300 Subject: [PATCH] feat: add before serialization hook --- source/orm/orm.entity/orm.base.entity.ts | 20 +++++++++++++++++++- source/test/person/person.entity.ts | 12 ++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/source/orm/orm.entity/orm.base.entity.ts b/source/orm/orm.entity/orm.base.entity.ts index bc87b0e..a5e40c2 100644 --- a/source/orm/orm.entity/orm.base.entity.ts +++ b/source/orm/orm.entity/orm.base.entity.ts @@ -1,5 +1,23 @@ -import { AnyEntity, BaseEntity } from '@mikro-orm/core'; +/* eslint-disable @typescript-eslint/naming-convention */ +import { AnyEntity, BaseEntity, wrap } from '@mikro-orm/core'; export abstract class OrmBaseEntity extends BaseEntity { + /** + * Extendable hook to apply custom steps before serialization. + * @param object + */ + protected beforeSerialization(object: any): any { + return object; + } + + /** + * Overwrites built-in serialization method to add hook. + * @param args + */ + public toJSON(...args: any[]): any { + const object = wrap(this, true).toObject(...args); + return this.beforeSerialization(object); + } + } diff --git a/source/test/person/person.entity.ts b/source/test/person/person.entity.ts index c8017e3..f2f59f9 100644 --- a/source/test/person/person.entity.ts +++ b/source/test/person/person.entity.ts @@ -32,4 +32,16 @@ export class PersonEntity extends OrmUuidTimestampEntity { @ManyToMany(() => CompanyEntity, company => company.employees) public employers = new Collection(this); + /** + * Join names. + * @param person + */ + protected beforeSerialization(person: PersonEntity): any { + const output: any = { ...person }; + output.fullName = `${output.name} ${output.surname}`; + delete output.name; + delete output.surname; + return output; + } + }