54 lines
1.8 KiB
TypeScript
54 lines
1.8 KiB
TypeScript
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<Test> {
|
|
|
|
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<Test> {
|
|
return Test.findOne({ where: test as any, })
|
|
}
|
|
|
|
filter(test: Test): Promise<Test[]> {
|
|
return Test.findAll({ where: test as any, })
|
|
}
|
|
|
|
async remove(id: number): Promise<number> {
|
|
return Test.destroy({ where: { id: id } });
|
|
}
|
|
|
|
async upsert(test: Test, insertIfNotFound: boolean): Promise<Test | [affectedCount: number]> {
|
|
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<any> {
|
|
const textbook = await firstValueFrom(this.httpService.get(`${Utility.urlConfig.textbookBaseUrl}${textbookId}`));
|
|
return textbook.data;
|
|
}
|
|
}
|