|
| 1 | +package com.accenture.codingtest.springbootcodingtest.service; |
| 2 | + |
| 3 | +import com.accenture.codingtest.springbootcodingtest.entity.Task; |
| 4 | +import com.accenture.codingtest.springbootcodingtest.repository.TaskRepository; |
| 5 | + |
| 6 | +import java.util.List; |
| 7 | +import java.util.Optional; |
| 8 | + |
| 9 | +import org.springframework.beans.factory.annotation.Autowired; |
| 10 | +import org.springframework.http.HttpStatus; |
| 11 | +import org.springframework.http.ResponseEntity; |
| 12 | +import org.springframework.stereotype.Service; |
| 13 | + |
| 14 | +@Service |
| 15 | +public class TaskService { |
| 16 | + |
| 17 | + @Autowired |
| 18 | + private TaskRepository taskRepository; |
| 19 | + |
| 20 | + public ResponseEntity<Task> saveTask(Task task) { |
| 21 | + ResponseEntity<Task> response = null; |
| 22 | + if (task != null) { |
| 23 | + response = new ResponseEntity<>(taskRepository.save(task), HttpStatus.OK); |
| 24 | + } else { |
| 25 | + response = new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); |
| 26 | + } |
| 27 | + return response; |
| 28 | + } |
| 29 | + public ResponseEntity<List<Task>> getAllTasks() { |
| 30 | + return new ResponseEntity<>(taskRepository.findAll(), HttpStatus.OK); |
| 31 | + } |
| 32 | + |
| 33 | + public ResponseEntity<Task> getTaskById(String id) { |
| 34 | + return new ResponseEntity<>(taskRepository.findById(id).get(), HttpStatus.OK); |
| 35 | + } |
| 36 | + |
| 37 | + public ResponseEntity<Task> updateTask(Task task) { |
| 38 | + ResponseEntity<Task> updatedTask = null; |
| 39 | + String id = task.getId(); |
| 40 | + Optional<Task> oldTaskOp = taskRepository.findById(id); |
| 41 | + |
| 42 | + if(oldTaskOp.isPresent()) { |
| 43 | + Task oldTask = oldTaskOp.get(); |
| 44 | + |
| 45 | + oldTask.setDescription(task.getDescription()); |
| 46 | + oldTask.setTitle(task.getTitle()); |
| 47 | + oldTask.setStatus(task.getStatus()); |
| 48 | + oldTask.setUser_id(task.getUser_id()); |
| 49 | + // oldTask.setProject_id(task.getProject_id()); |
| 50 | + |
| 51 | + updatedTask = new ResponseEntity<>(taskRepository.save(oldTask), HttpStatus.OK); |
| 52 | + } else { |
| 53 | + updatedTask = new ResponseEntity<>(HttpStatus.NOT_FOUND); |
| 54 | + } |
| 55 | + |
| 56 | + return updatedTask; |
| 57 | + } |
| 58 | + |
| 59 | + public ResponseEntity<Void> deleteTask(String id) { |
| 60 | + ResponseEntity<Void> response = null; |
| 61 | + if (taskRepository.existsById(id)) { |
| 62 | + taskRepository.deleteById(id); |
| 63 | + response = new ResponseEntity<>(HttpStatus.OK); |
| 64 | + } else { |
| 65 | + response = new ResponseEntity<>(HttpStatus.NOT_FOUND); |
| 66 | + } |
| 67 | + return response; |
| 68 | + } |
| 69 | +} |
0 commit comments