Reputation: 91
I have the service that gives data from repository to rest controller:
@Service
public class TaskServiceImpl implements TaskService {
@Autowired
private TaskRepository taskRepository;
@Override
public List<Task> getAllTasks() {
return taskRepository.findAll();
}
}
And also rest controller: @RestController @RequestMapping("/tasks") public class TaskController { @Autowired private TaskService taskService;
@GetMapping
public List<Task> getAllTasks() {
return taskService.getAllTasks();
}
}
My task is to return not only all the tasks but two fields two - todo tasks count and ready tasks count. I know how find this count from db. But what is the proper way to add this fields to response json? Response json must look like:
{
[
{
"createTime": null,
"updateTime": null,
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"title": "todo-task",
"description": "blabla",
"priority": "HIGH",
"done": false,
},
{
"createTime": null,
"updateTime": null,
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"title": "done-task",
"description": "blabla",
"priority": "HIGH",
"done": true,
}
],
todoCount: 1,
doneCount: 1
}
Upvotes: 1
Views: 2178
Reputation: 2413
you can do that by creating new model to be returned by the Controller and set your todoCount and doneCount values:
@GetMapping
public TasksModel getAllTasks() {
// get todoCount and doneCount values
TasksModel tasksModel = new TasksModel();
tasksModel.setTaskModelList(taskService.getAllTasks())
tasksModel.setTodoCount(todoCount);
tasksModel.setDoneCount(doneCount);
return taskModel;
}
and TasksModel is :
class TasksModel {
List<Task> taskModelList;
int todoCount;
int doneCount;
//getter
//setter
}
Upvotes: 0