From 3eafdd7f406d6c6d28644defb80874d83a2ddfb0 Mon Sep 17 00:00:00 2001
From: L4168 <L4168@student.jamk.fi>
Date: Thu, 27 Jun 2019 11:46:11 +0300
Subject: [PATCH] updated newTask and created editTask service

---
 src/task/task.service.ts | 42 ++++++++++++++++++++++++++++++++++++++--
 1 file changed, 40 insertions(+), 2 deletions(-)

diff --git a/src/task/task.service.ts b/src/task/task.service.ts
index 830e615..7df6dee 100644
--- a/src/task/task.service.ts
+++ b/src/task/task.service.ts
@@ -2,20 +2,58 @@ import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
 import { Repository } from 'typeorm';
 import { InjectRepository } from '@nestjs/typeorm';
 import { TaskEntity } from './task.entity';
-import { TaskDTO } from './task.dto';
+import { CreateTaskDTO, EditTaskDTO } from './task.dto';
+import { FactionEntity } from '../game/faction.entity';
 
 @Injectable()
 export class TaskService {
   constructor(
     @InjectRepository(TaskEntity)
     private taskRepository: Repository<TaskEntity>,
+    @InjectRepository(FactionEntity)
+    private factionRepository: Repository<FactionEntity>,
   ) {}
 
-  async newTask(task: TaskDTO) {
+  async newTask(task: CreateTaskDTO) {
+    // check if is not null, check that the faction exists in the game
+    if (
+      task.faction != null &&
+      !(await this.factionRepository.findOne({
+        factionId: task.faction.toString(),
+        game: task.taskGame,
+      }))
+    ) {
+      throw new HttpException('Faction not found', HttpStatus.BAD_REQUEST);
+    }
     const createdTask = await this.taskRepository.create(task);
+    console.log(createdTask);
     await this.taskRepository.insert(createdTask);
     return {
       message: 'Task added',
     };
   }
+
+  async editTask(data: EditTaskDTO) {
+    const task = await this.taskRepository.findOne(data.taskId);
+    console.log(task);
+    // checks if task is already closed
+    if (!task.taskIsActive) {
+      throw new HttpException('Task is not active', HttpStatus.BAD_REQUEST);
+    }
+    // checks if faction is valid
+    if (
+      !(await this.factionRepository.findOne({
+        factionId: data.taskWinner.toString(),
+        game: data.taskGame,
+      }))
+    ) {
+      throw new HttpException('Faction not found', HttpStatus.BAD_REQUEST);
+    }
+    task.taskWinner = data.taskWinner;
+    task.taskIsActive = false;
+    await this.taskRepository.save(task);
+    return {
+      message: 'Task updated and closed',
+    };
+  }
 }
-- 
GitLab