Skip to content

Commit

Permalink
feat: add before serialization hook
Browse files Browse the repository at this point in the history
  • Loading branch information
etienne-bechara committed May 31, 2021
1 parent dbeee42 commit 161a3ab
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
20 changes: 19 additions & 1 deletion source/orm/orm.entity/orm.base.entity.ts
Original file line number Diff line number Diff line change
@@ -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<AnyEntity, 'id'> {

/**
* 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);
}

}
12 changes: 12 additions & 0 deletions source/test/person/person.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,16 @@ export class PersonEntity extends OrmUuidTimestampEntity {
@ManyToMany(() => CompanyEntity, company => company.employees)
public employers = new Collection<CompanyEntity>(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;
}

}

0 comments on commit 161a3ab

Please sign in to comment.