Nestjs TypeORM create and payment seed,
The findall function looks for the specified data in the database and you can retrieve the data with a get request and the correct endpoint. The payment function adds the payment data to the members data table. Which we indicated in the entity. In the payment table, we also specify the amount of the payment and when exactly it was created. Then we create an error message to check that we worked well.
This is just an example, but I think the process of thought can be useful for the creator
async pay(id: number) {
const memberRepo = this.dataSource.getRepository(Members);
const paymentRepo = this.dataSource.getRepository(Payments);
let MemberExist = await memberRepo.findOne({ where: { id: id } });
if (!MemberExist) {
throw new NotFoundException('Ez az azonosítójú tag nem találhato');
}
const paymentsByMember = await paymentRepo.find({
where: { member_id: { id: MemberExist.id } },
relations: { member_id: true },
});
let paidThisMonth = false;
let today = new Date();
for (let i = 0; i < paymentsByMember.length; i++) {
if (
paymentsByMember[i].paid_at.getFullYear() == today.getFullYear() &&
paymentsByMember[i].paid_at.getMonth() == today.getMonth()
) {
paidThisMonth = true;
}
}
if (paidThisMonth) {
throw new ConflictException('Ebben a hónapban már fizetett');
}
let newPayment: Payments = {
id: 0,
member_id: MemberExist,
amount: 5000,
paid_at: today,
};
paymentRepo.save(newPayment);
}
async create(createMemberDto: CreateMemberDto) {
await this.dataSource.getRepository(Members).save(createMemberDto);
}
async findAll() {
return {
data: await this.dataSource.getRepository(Members).find({
select: {
id: true,
name: true,
gender: true,
birth_date: true,
created_at: true,
},
}),
};
}