2025SELab2-project-Dwengo/backend/src/data/questions/question-repository.ts
2025-04-07 16:34:12 +02:00

80 lines
3.3 KiB
TypeScript

import { DwengoEntityRepository } from '../dwengo-entity-repository.js';
import { Question } from '../../entities/questions/question.entity.js';
import { LearningObjectIdentifier } from '../../entities/content/learning-object-identifier.js';
import { Student } from '../../entities/users/student.entity.js';
import { LearningObject } from '../../entities/content/learning-object.entity.js';
import {Loaded} from "@mikro-orm/core";
export class QuestionRepository extends DwengoEntityRepository<Question> {
public async createQuestion(question: { loId: LearningObjectIdentifier; author: Student; content: string }): Promise<Question> {
const questionEntity = this.create({
learningObjectHruid: question.loId.hruid,
learningObjectLanguage: question.loId.language,
learningObjectVersion: question.loId.version,
author: question.author,
content: question.content,
timestamp: new Date(),
});
questionEntity.learningObjectHruid = question.loId.hruid;
questionEntity.learningObjectLanguage = question.loId.language;
questionEntity.learningObjectVersion = question.loId.version;
questionEntity.author = question.author;
questionEntity.content = question.content;
return this.insert(questionEntity);
}
public async findAllQuestionsAboutLearningObject(loId: LearningObjectIdentifier): Promise<Question[]> {
return this.findAll({
where: {
learningObjectHruid: loId.hruid,
learningObjectLanguage: loId.language,
learningObjectVersion: loId.version,
},
orderBy: {
sequenceNumber: 'ASC',
},
});
}
public async removeQuestionByLearningObjectAndSequenceNumber(loId: LearningObjectIdentifier, sequenceNumber: number): Promise<void> {
return this.deleteWhere({
learningObjectHruid: loId.hruid,
learningObjectLanguage: loId.language,
learningObjectVersion: loId.version,
sequenceNumber: sequenceNumber,
});
}
public async findAllByLearningObjects(learningObjects: LearningObject[]): Promise<Question[]> {
const objectIdentifiers = learningObjects.map((lo) => ({
learningObjectHruid: lo.hruid,
learningObjectLanguage: lo.language,
learningObjectVersion: lo.version,
}));
return this.findAll({
where: { $or: objectIdentifiers },
orderBy: { timestamp: 'ASC' },
});
}
public async findAllByAuthor(author: Student): Promise<Question[]> {
return this.findAll({
where: { author },
orderBy: { timestamp: 'DESC' }, // New to old
});
}
public async findByLearningObjectAndSequenceNumber(loId: LearningObjectIdentifier, sequenceNumber: number): Promise<Loaded<Question> | null> {
return this.findOne({
learningObjectHruid: loId.hruid,
learningObjectLanguage: loId.language,
learningObjectVersion: loId.version,
sequenceNumber
});
}
public async updateContent(question: Question, newContent: string): Promise<Question> {
question.content = newContent;
await this.save(question);
return question;
}
}