freetubesync/FreeTubeSync/EndPoints/ProfileEndpoint.cs
Mario Steele 73955353cb Possibly fix issues
After doing testing with a test project, re-organized code to new method
of storing, as well as ensure that all Endpoint lambda's are separated
out into functions.

Large commit, will be testing.
2025-08-08 16:59:29 -05:00

80 lines
No EOL
2.6 KiB
C#

using FreeTubeSync.Model;
namespace FreeTubeSync.EndPoints;
public static class ProfileEndpoint
{
public static void MapProfileEndpoints(this WebApplication app)
{
var group = app.MapGroup("profile");
group.MapGet("/", GetAllProfiles);
group.MapGet("/{id}", GetProfile);
group.MapPost("/", UpdateProfile);
group.MapDelete("/{id}", DeleteProfile);
}
private static async Task<IResult> GetAllProfiles(IRepository<Profile> repository, CancellationToken ct)
{
var results = await repository.GetAllAsync(ct);
return Results.Ok(results);
}
private static async Task<IResult> GetProfile(IRepository<Profile> repository, string id, CancellationToken ct)
{
var result = await repository.GetByIdAsync(id, ct);
return result == null ? Results.NotFound() : Results.Ok(result);
}
private static async Task<IResult> UpdateProfile(IRepository<Profile> repository, Profile profile, CancellationToken ct, ILogger<Program> logger)
{
var res = await repository.GetByIdAsync(profile._id, ct);
if (res == null)
{
try
{
await repository.AddAsync(profile, ct);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to create profile {json}", profile._id);
return Results.StatusCode(500);
}
}
else
{
var toRemove = res.subscriptions.Where(sub => !profile.subscriptions.Any(x => x.id == sub.id)).ToList();
res.name = profile.name;
res.textColor = profile.textColor;
res.bgColor = profile.bgColor;
foreach (var sub in toRemove)
res.subscriptions.Remove(sub);
foreach (var sub in profile.subscriptions)
{
var osub = res.subscriptions.FirstOrDefault(x => x.id == sub.id);
if (osub == null)
res.subscriptions.Add(sub);
else
{
osub.name = sub.name;
osub.thumbnail = sub.thumbnail;
}
}
await repository.UpdateAsync(res, ct);
}
return Results.Ok();
}
private static async Task<IResult> DeleteProfile(IRepository<Profile> repository, string id, CancellationToken ct)
{
var result = await repository.GetByIdAsync(id, ct);
if (result == null) return Results.NotFound();
await repository.DeleteAsync(result, ct);
return Results.Ok();
}
}