Skip to content

Commit

Permalink
fix(core): allow populating FK as PK in toJSON()
Browse files Browse the repository at this point in the history
Previously when entity was used as PK, it was always serialized to that entity PK.
With this fix, it will respect the populate parameter.
  • Loading branch information
B4nan committed Aug 9, 2020
1 parent 9736a17 commit e05d780
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 5 deletions.
16 changes: 13 additions & 3 deletions packages/core/src/entity/EntityTransformer.ts
Expand Up @@ -15,8 +15,18 @@ export class EntityTransformer {

meta.primaryKeys
.filter(pk => !Utils.isDefined(entity[pk], true) || !(meta.properties[pk].hidden || ignoreFields.includes(pk)))
.map(pk => [pk, Utils.getPrimaryKeyValue<T>(entity, [pk])] as [string, string])
.forEach(([pk, value]) => ret[platform.getSerializedPrimaryKeyField(pk) as keyof T] = platform.normalizePrimaryKey(value));
.map(pk => {
let value: unknown;

if (Utils.isEntity(entity[pk], true)) {
value = EntityTransformer.processEntity(pk, entity, ignoreFields, visited);
} else {
value = platform.normalizePrimaryKey(Utils.getPrimaryKeyValue<T>(entity, [pk]));
}

return [pk, value] as [string, string];
})
.forEach(([pk, value]) => ret[platform.getSerializedPrimaryKeyField(pk) as keyof T] = value as unknown as T[keyof T]);

if ((!wrapped.isInitialized() && Utils.isDefined(wrapped.__primaryKey, true)) || visited.includes(wrapped.__uuid)) {
return ret;
Expand Down Expand Up @@ -63,7 +73,7 @@ export class EntityTransformer {
return EntityTransformer.processCollection(prop, entity);
}

if (Utils.isEntity(entity[prop]) || entity[prop] as unknown instanceof Reference) {
if (Utils.isEntity(entity[prop], true)) {
return EntityTransformer.processEntity(prop, entity, ignoreFields, visited);
}

Expand Down
1 change: 0 additions & 1 deletion packages/core/src/entity/wrap.ts
@@ -1,6 +1,5 @@
import { Dictionary, IWrappedEntity, IWrappedEntityInternal } from '../typings';
import { ArrayCollection } from './ArrayCollection';
import { WrappedEntity } from './WrappedEntity';
import { BaseEntity } from './BaseEntity';

/**
Expand Down
6 changes: 5 additions & 1 deletion tests/composite-keys.mysql.test.ts
Expand Up @@ -35,7 +35,11 @@ describe('composite keys in mysql', () => {
await orm.em.persistAndFlush(param);
orm.em.clear();

const p1 = await orm.em.findOneOrFail(FooParam2, [param.bar.id, param.baz.id]);
// test populating a PK
const p1 = await orm.em.findOneOrFail(FooParam2, [param.bar.id, param.baz.id], ['bar']);
expect(wrap(p1).toJSON().bar).toMatchObject(wrap(p1.bar).toJSON());
expect(wrap(p1).toJSON().baz).toBe(p1.baz.id);

expect(p1.bar.id).toBe(bar.id);
expect(p1.baz.id).toBe(baz.id);
expect(p1.value).toBe('val');
Expand Down

0 comments on commit e05d780

Please sign in to comment.