Skip to content

Commit

Permalink
feat: awaitable endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
tdayko committed Apr 20, 2024
1 parent b824e7b commit b8f879c
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 22 deletions.
4 changes: 2 additions & 2 deletions src/HigiaServer.API/Endpoints/AuthenticationEndpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ private static async Task<IResult> HandleRegister(
IJwtTokenService jwtTokenService
)
{
if (repository.GetUserByEmail(request.Email) != null) throw new DuplicateEmailException(request.Email);
if (await repository.GetUserByEmail(request.Email) != null) throw new DuplicateEmailException(request.Email);

request.Password = BCrypt.Net.BCrypt.HashPassword(request.Password);
var user = mapper.Map<User>(request);
Expand All @@ -69,7 +69,7 @@ private static async Task<IResult> HandleLogin(
IJwtTokenService jwtTokenService
)
{
if (repository.GetUserByEmail(request.Email) is not { } user) throw new EmailGivenNotFoundException(request.Email);
if (await repository.GetUserByEmail(request.Email) is not { } user) throw new EmailGivenNotFoundException(request.Email);
if (!BCrypt.Net.BCrypt.Verify(request.Password, user.Password)) throw new InvalidPasswordException();

var authResponse = new AuthenticationResponse(
Expand Down
70 changes: 51 additions & 19 deletions src/HigiaServer.API/Endpoints/TaskEndpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,15 @@
using HigiaServer.Application.Contracts.Responses;
using HigiaServer.Application.Errors;
using HigiaServer.Application.Repositories;
using Task = HigiaServer.Domain.Entities.Task;
using HigiaServer.Domain.Enums;

namespace HigiaServer.API.Endpoints;

public static class TaskEndpoint
{
public static IEndpointRouteBuilder AddTaskEndpoint(this IEndpointRouteBuilder app)
{
var authEndpoint = app.MapGroup("higia-server/api/tasks")
.WithTags("Tasks");
var authEndpoint = app.MapGroup("higia-server/api/tasks").WithTags("Tasks");

// add task
authEndpoint.MapPost("/", HandleAddTask)
Expand All @@ -25,9 +24,9 @@ public static IEndpointRouteBuilder AddTaskEndpoint(this IEndpointRouteBuilder a
x.Summary = "Add Tasks";
return x;
});

// get task by id
authEndpoint.MapGet("/{taskId}", GetTask)
authEndpoint.MapGet("/{taskId}", HandleGetTask)
.WithName("Get task by id")
.Produces<TaskResponse>()
.WithOpenApi(x =>
Expand All @@ -36,47 +35,80 @@ public static IEndpointRouteBuilder AddTaskEndpoint(this IEndpointRouteBuilder a
return x;
});

authEndpoint.MapPatch("/{taskId}/{status}", HandleUpdateTaskStatus)
.WithName("Update Task Status")
.WithOpenApi(x =>
{
x.Summary = "Get task by id";
return x;
});

return app;
}

#region private methods


private static async Task<IResult> HandleUpdateTaskStatus(
HttpContext context,
string taskId,
Status status,
ITaskRepository taskRepository
)
{
CheckAuthorizationAsAdministrator(context);
if (!Guid.TryParse(taskId, out var id)) throw new NonGuidTypeException(taskId);
var task = await taskRepository.GetTaskById(id) ?? throw new TaskIdGivenNotFoundException(id.ToString());

task.UpdateTaskStatus(status);
taskRepository.UpdateTask(task);

context.Response.Headers.Location = $"{context.Request.Scheme}://{context.Request.Host}/{context.Request.Path}/{task.Id}";
return Results.Ok();
}

private static async Task<IResult> HandleAddTask(
HttpContext context,
AddTaskRequest request,
IUserRepository userRepository,
ITaskRepository taskRepository,
IMapper mapper)
IMapper mapper
)
{
if (!context.User!.Identity!.IsAuthenticated) throw new UnauthenticatedException();
if (context.User.FindFirstValue(ClaimTypes.Role) == "collaborator") throw new UnauthorizedAccessException();
var task = mapper.Map<Task>(request);

var collaborators = request.CollaboratorsId
.Select(id => userRepository.GetUserById(id) ?? throw new CollaboratorIdNotFound(id.ToString()))
CheckAuthorizationAsAdministrator(context);
var task = mapper.Map<Domain.Entities.Task>(request);

var collaborators = (await Task.WhenAll(request.CollaboratorsId
.Select(async id => await userRepository.GetUserById(id) ?? throw new CollaboratorIdNotFound(id.ToString()))))
.ToList();

task.AddCollaboratorsToTask(collaborators);
taskRepository.AddTask(task);

var location = new Uri($"{context.Request.Scheme}://{context.Request.Host}/{context.Request.Path}/{task.Id}");

var taskResponse = mapper.Map<TaskResponse>(task);
return Results.Created(location, new StandardSuccessResponse<TaskResponse>(taskResponse, location));
}

private static async Task<IResult> GetTask(
private static async Task<IResult> HandleGetTask(
HttpContext context,
string taskId,
ITaskRepository taskRepository,
IMapper mapper)
IMapper mapper
)
{
if (!context.User!.Identity!.IsAuthenticated) throw new AuthenticationException();
if (!Guid.TryParse(taskId, out var id)) throw new NonGuidTypeException(taskId);

var task = taskRepository.GetTaskById(id) ?? throw new TaskIdGivenNotFoundException(id.ToString());
var task = await taskRepository.GetTaskById(id) ?? throw new TaskIdGivenNotFoundException(id.ToString());

var taskResponse = mapper.Map<TaskResponse>(task);
return Results.Ok(new StandardSuccessResponse<TaskResponse>(taskResponse));
}


private static void CheckAuthorizationAsAdministrator(HttpContext context)
{
if (!context.User!.Identity!.IsAuthenticated) throw new UnauthenticatedException();
if (context.User.FindFirstValue(ClaimTypes.Role) != "admin") throw new UnauthorizedAccessException();
}
#endregion
}
}
2 changes: 1 addition & 1 deletion src/HigiaServer.Domain/Entities/Task.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class Task(

public void AddCollaboratorToTask(User user) => Collaborators.Add(user);

public void AddCollaboratorsToTask(IEnumerable<User> user) => Collaborators.AddRange(user);
public void AddCollaboratorsToTask(List<User> user) => Collaborators.AddRange(user);

public void UpdateTaskStatus(Status newStatus) => Status = newStatus;
}

0 comments on commit b8f879c

Please sign in to comment.