78 lines
2.7 KiB
C#
78 lines
2.7 KiB
C#
using System.Net.Http.Json;
|
|
using Tasks.Module.Models;
|
|
|
|
namespace Tasks.Module.Services;
|
|
|
|
public interface ITodoService
|
|
{
|
|
Task<List<TodoItemDto>> GetAllTodosAsync(TodoFilterDto? filter = null);
|
|
Task<TodoItemDto?> GetTodoByIdAsync(string id);
|
|
Task<TodoItemDto> CreateTodoAsync(CreateTodoItemDto createDto);
|
|
Task<TodoItemDto?> UpdateTodoAsync(UpdateTodoItemDto updateDto);
|
|
Task<bool> DeleteTodoAsync(string id);
|
|
Task<TodoItemDto?> ToggleCompleteAsync(string id);
|
|
}
|
|
|
|
public class TodoService : ITodoService
|
|
{
|
|
private readonly HttpClient _httpClient;
|
|
|
|
public TodoService(HttpClient httpClient)
|
|
{
|
|
_httpClient = httpClient;
|
|
}
|
|
|
|
public async Task<List<TodoItemDto>> GetAllTodosAsync(TodoFilterDto? filter = null)
|
|
{
|
|
var url = $"/api/v1/todos";
|
|
|
|
var queryParams = new List<string>();
|
|
if (filter?.IsCompleted != null)
|
|
queryParams.Add($"isCompleted={filter.IsCompleted}");
|
|
if (filter?.Priority != null)
|
|
queryParams.Add($"priority={filter.Priority}");
|
|
if (filter?.DueDate != null)
|
|
queryParams.Add($"dueDate={filter.DueDate:yyyy-MM-ddTHH:mm:ssZ}");
|
|
if (!string.IsNullOrEmpty(filter?.ParentId))
|
|
queryParams.Add($"parentId={filter.ParentId}");
|
|
|
|
if (queryParams.Any())
|
|
url += "?" + string.Join("&", queryParams);
|
|
|
|
return await _httpClient.GetFromJsonAsync<List<TodoItemDto>>(url) ?? new List<TodoItemDto>();
|
|
}
|
|
|
|
public async Task<TodoItemDto?> GetTodoByIdAsync(string id)
|
|
{
|
|
return await _httpClient.GetFromJsonAsync<TodoItemDto>($"/api/v1/todos/{id}");
|
|
}
|
|
|
|
public async Task<TodoItemDto> CreateTodoAsync(CreateTodoItemDto createDto)
|
|
{
|
|
var response = await _httpClient.PostAsJsonAsync("/api/v1/todos", createDto);
|
|
response.EnsureSuccessStatusCode();
|
|
return await response.Content.ReadFromJsonAsync<TodoItemDto>() ?? throw new Exception("Failed to create todo");
|
|
}
|
|
|
|
public async Task<TodoItemDto?> UpdateTodoAsync(UpdateTodoItemDto updateDto)
|
|
{
|
|
var response = await _httpClient.PutAsJsonAsync("/api/v1/todos", updateDto);
|
|
if (!response.IsSuccessStatusCode)
|
|
return null;
|
|
return await response.Content.ReadFromJsonAsync<TodoItemDto>();
|
|
}
|
|
|
|
public async Task<bool> DeleteTodoAsync(string id)
|
|
{
|
|
var response = await _httpClient.DeleteAsync($"/api/v1/todos/{id}");
|
|
return response.IsSuccessStatusCode;
|
|
}
|
|
|
|
public async Task<TodoItemDto?> ToggleCompleteAsync(string id)
|
|
{
|
|
var response = await _httpClient.PatchAsync($"/api/v1/todos/{id}/toggle", null);
|
|
if (!response.IsSuccessStatusCode)
|
|
return null;
|
|
return await response.Content.ReadFromJsonAsync<TodoItemDto>();
|
|
}
|
|
} |