Service Layer
Let's implement the business logic to update a task.
Update the Task Service
We'll start by updating the TaskService interface.
We'll define a new method to update a task, using the UpdateTaskRequest
object we just created:
/**
* Updates the specified task.
*
* @param taskId The ID of the task to update.
* @param request The request object used to update the task.
* @return The updated task.
*/
Task updateTask(UUID taskId, UpdateTaskRequest request);We've specified two arguments to the updateTask method. One is the
UpdateTaskRequest object, and the other is the ID of the task to update.
We specify the task ID as its own argument as it will be passed in the URL path, not the request body.
Let's implement our new method!
Implement the Update Task Method
Over in the TaskServiceImpl class, let's implement our new method:
@Override
public Task updateTask(UUID taskId, UpdateTaskRequest request) {
// Look up the existing task. If it doesn't exist
// throw a TaskNotFoundException
Task existingTask = taskRepository.findById(taskId).orElseThrow(() ->
new TaskNotFoundException(taskId)
);
// Update the existing task with the provided information.
existingTask.setTitle(request.title());
existingTask.setDescription(request.description());
existingTask.setDueDate(request.dueDate());
existingTask.setPriority(request.priority());
existingTask.setStatus(request.status());
// Update the existing task's updated value.
existingTask.setUpdated(Instant.now());
// Save the existing task.
return taskRepository.save(existingTask);
}Our new method looks up the existing task from the database, updates it
using the provided values, and saves the changes. A TaskNotFoundException is
thrown if the task does not exist.
That's it for the service layer, let's create the DTOs and mapper methods we'll use in the presentation layer.
Summary
- Updated the
TaskServiceinterface. - Implemented the
updateTaskmethod.