Skip to content

Commit

Permalink
refactor: call convertToJSValue when mapping PKs
Browse files Browse the repository at this point in the history
Related: #435
  • Loading branch information
Martin Adamek committed Mar 31, 2020
1 parent 3cf3da6 commit 6b18373
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
10 changes: 8 additions & 2 deletions lib/unit-of-work/ChangeSetPersister.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,21 @@ export class ChangeSetPersister {
} else { // ChangeSetType.CREATE without primary key
res = await this.driver.nativeInsert(changeSet.name, changeSet.payload, ctx);
this.mapReturnedValues(changeSet.entity, res, meta);
wrap(changeSet.entity).__primaryKey = Utils.isDefined(changeSet.entity.__primaryKey, true) ? changeSet.entity.__primaryKey : res.insertId as any;
this.identifierMap[changeSet.entity.__uuid].setValue(changeSet.entity.__primaryKey as IPrimaryKey);
this.mapPrimaryKey(meta, res, changeSet);
delete changeSet.entity.__initialized;
}

await this.processOptimisticLock(meta, changeSet, res, ctx);
changeSet.persisted = true;
}

private mapPrimaryKey<T>(meta: EntityMetadata<T>, res: QueryResult, changeSet: ChangeSet<T>): void {
const prop = meta.properties[meta.primaryKeys[0]];
const insertId = prop.customType ? prop.customType.convertToJSValue(res.insertId, this.driver.getPlatform()) : res.insertId;
wrap(changeSet.entity).__primaryKey = Utils.isDefined(changeSet.entity.__primaryKey, true) ? changeSet.entity.__primaryKey : insertId;
this.identifierMap[changeSet.entity.__uuid].setValue(changeSet.entity[prop.name] as unknown as IPrimaryKey);
}

private async updateEntity<T extends AnyEntity<T>>(meta: EntityMetadata<T>, changeSet: ChangeSet<T>, ctx?: Transaction): Promise<QueryResult> {
if (!meta.versionProperty || !changeSet.entity[meta.versionProperty]) {
return this.driver.nativeUpdate(changeSet.name, changeSet.entity.__primaryKey as {}, changeSet.payload, ctx);
Expand Down
6 changes: 2 additions & 4 deletions tests/entities-sql/BookTag2.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { BigIntType, Collection, Entity, ManyToMany, PrimaryKey, Property, ReferenceType } from '../../lib';
import { BigIntType, Collection, Entity, ManyToMany, PrimaryKey, Property, ReferenceType, wrap } from '../../lib';
import { Book2 } from './Book2';
import { MetadataStorage } from '../../lib/metadata';

@Entity()
export class BookTag2 {
Expand All @@ -18,8 +17,7 @@ export class BookTag2 {
booksUnordered!: Collection<Book2>;

constructor(name: string) {
const meta = MetadataStorage.getMetadata(this.constructor.name);
const props = meta.properties;
const props = wrap(this).__meta.properties;

Object.keys(props).forEach(prop => {
if ([ReferenceType.ONE_TO_MANY, ReferenceType.MANY_TO_MANY].includes(props[prop].reference)) {
Expand Down

0 comments on commit 6b18373

Please sign in to comment.