backend/src/models/entities/DistanceDonation.ts

49 lines
1.2 KiB
TypeScript

import { IsInt, IsNotEmpty, IsPositive } from "class-validator";
import { ChildEntity, Column, ManyToOne } from "typeorm";
import { Donation } from "./Donation";
import { Runner } from "./Runner";
/**
* Defines a distance based donation.
* Here people donate a certain amout per kilometer
*/
@ChildEntity()
export class DistanceDonation extends Donation {
/**
* The runner associated.
*/
@IsNotEmpty()
@ManyToOne(() => Runner, runner => runner.distanceDonations, { nullable: true })
runner: Runner;
/**
* The amount the donor set to be donated per kilometer that the runner ran.
*/
@Column()
@IsInt()
@IsPositive()
amountPerDistance: number;
/**
* The donation's amount in cents (or whatever your currency's smallest unit is.).
* The exact implementation may differ for each type of donation.
*/
@IsInt()
public get amount() {
return this.getAmount();
}
/**
* The function that calculates the amount based on the runner object's distance.
*/
public async getAmount(): Promise<number> {
let calculatedAmount = -1;
try {
calculatedAmount = this.amountPerDistance * await this.runner.distance();
} catch (error) {
throw error;
}
return calculatedAmount;
}
}