【发布时间】:2020-10-20 21:23:44
【问题描述】:
我正在尝试编写一个工厂来更新实体,但使用后加载会引发错误:
实体:
import {
Entity,
PrimaryGeneratedColumn,
Column,
OneToMany,
BaseEntity,
AfterLoad,
} from "typeorm";
import { OtherEntity } from "./OtherEntity";
// ColumnNumericTransformer
export class ColumnNumericTransformer {
to(data: number): number {
return data;
}
from(data: string): number {
return parseFloat(data);
}
}
@Entity()
export class EntityExample extends BaseEntity {
@PrimaryGeneratedColumn("uuid")
id: string;
@Column()
name: string;
@Column("numeric", {
precision: 7,
scale: 2,
transformer: new ColumnNumericTransformer(),
default: 0,
})
GGR: number;
@Column("numeric", {
precision: 7,
scale: 2,
transformer: new ColumnNumericTransformer(),
default: 0,
})
bets: number;
@Column("numeric", {
precision: 7,
scale: 2,
transformer: new ColumnNumericTransformer(),
default: 0,
})
wins: number;
@Column({ default: 0 })
fee_percentage: number;
@Column("numeric", {
precision: 7,
scale: 2,
transformer: new ColumnNumericTransformer(),
default: 0,
})
fee_amount: number;
@OneToMany((type) => OtherEntity, (some) => some.data)
relations: OtherEntity[];
@AfterLoad()
setComputed() {
this.GGR = this.bets - this.wins;
this.fee_amount = this.GGR * (this.fee_percentage/100);
}
}
工厂:
update: async(attrs: Partial<EntityExample> = {}) => {
let entityExample = await getRepository(EntityExample).findOne(attrs.id);
entityExample = {...entityExample, ...attrs};
let updated_entity_example;
try {
updated_entity_example = await getRepository(EntityExample).save(entityExample);
} catch (e) {
throw new Error("Couln't save Entity Example")
}
return updated_entity_example
}
TypeORM 错误:
Property 'setComputed' is optional in type '{ id: string; name: string; GGR: number; bets: number; wins: number; fee_percentage: number; fee_amount: number; setComputed?: () => void; hasId?: () => boolean; save?: (options?: SaveOptions) => Promise<...>; remove?: (options?: RemoveOptions) => Promise<...>; softRemove?: (options?: SaveOptions...' but required in type 'EntityExample'
那么,问题是我该如何解决呢?我应该每次都将 setComputed 传递给工厂吗?或者,还有更好的方法?也许值得使用不同的方法?哪些比较好?
【问题讨论】:
标签: node.js typescript typeorm