0
I have quiz api in nestjs, i am using typeORM for saving data, I want to do following transaction:
- create quiz in quiz table with title and auto generated Id and empty array of questions
- for each question try to save question in data base with generated quiz_id and questions input
- save quiz and commit transaction
I am trying to test it but it dosent work
this is my create quiz operation:
async createQuiz(createQuizInput: CreateQuizInput): Promise <Quiz>{
const {title, questions} = createQuizInput;
const queryRunner = this.dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try{
let quiz = this.quizRepository.create({title});
quiz = await queryRunner.manager.save(quiz)
for(const question of questions){
const questionsToSave = await this.questionService.createQuestion(quiz.id, question);
await queryRunner.manager.save(questionsToSave)
quiz.questions.push(questionsToSave)
}
await queryRunner.manager.save(quiz);
await queryRunner.commitTransaction();
return quiz;
}
catch(err){
await queryRunner.rollbackTransaction();
throw new Error(err)
}
finally{
await queryRunner.release();
}
}
my quesions is: how to fix following bug:
{
"errors": [
{
"message": "Error: QueryFailedError: insert or update on table "question" violates foreign key constraint "FK_4959a4225f25d923111e54c7cd2"",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"createQuiz"
],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"stacktrace": [
"Error: Error: QueryFailedError: insert or update on table "question" violates foreign key constraint "FK_4959a4225f25d923111e54c7cd2"",
" at QuizService.createQuiz