import { Injectable } from '@nestjs/common'; import Test from './test.entity'; import { firstValueFrom } from 'rxjs'; import { HttpService } from "@nestjs/axios"; import { Utility } from 'src/common/Utility'; @Injectable() export class TestService { constructor(private readonly httpService: HttpService) { } async findAll(): Promise<{ rows: Test[], count: number }> { return Test.findAndCountAll(); } async findByPk(id: number): Promise { const test = Test.findByPk(id,) const textbookExists = await this.checkTextbookExists((await test).textbookId); if (!textbookExists.data.author) return; console.log(textbookExists.data.author); return test } findOne(test: Test): Promise { return Test.findOne({ where: test as any, }) } filter(test: Test): Promise { return Test.findAll({ where: test as any, }) } async remove(id: number): Promise { return Test.destroy({ where: { id: id } }); } async upsert(test: Test, insertIfNotFound: boolean): Promise { if (test.id) { const existingTest = await this.findByPk(test.id); if (existingTest) { return Test.update(test, { where: { id: test.id } }); } } if (insertIfNotFound) { const textbookExists = await this.checkTextbookExists(test.textbookId); if (!textbookExists) return; return Test.create(test as any) } } async checkTextbookExists(textbookId: number): Promise { const textbook = await firstValueFrom(this.httpService.get(`${Utility.urlConfig.textbookBaseUrl}${textbookId}`)); return textbook.data; } }