Added an UpdateAsync() call for each subscription, to ensure that subscriptions actually get updated in the database.
93 lines
No EOL
3.4 KiB
C#
93 lines
No EOL
3.4 KiB
C#
using FreeTubeSync.Database;
|
|
using FreeTubeSync.Model.Database;
|
|
using FreeTubeSync.Model.Json;
|
|
|
|
namespace FreeTubeSync.EndPoints;
|
|
|
|
public static class ProfileEndpoint
|
|
{
|
|
public static void MapProfileEndpoints(this WebApplication app)
|
|
{
|
|
var group = app.MapGroup("profile");
|
|
|
|
group.MapGet("/", async (IRepository<Profile> repository, CancellationToken ct) =>
|
|
{
|
|
var results = (await repository.GetAllAsync(ct)).ToList();
|
|
var jsonResults = new List<ProfileJson>();
|
|
results.MapTo(jsonResults);
|
|
for (var i = 0; i < jsonResults.Count; i++)
|
|
results[i].subscriptions.MapTo(jsonResults[i].subscriptions);
|
|
return Results.Ok(results);
|
|
});
|
|
|
|
group.MapPost("/", async (IRepository<Profile> repository, IRepository<Subscription> subRepo, CancellationToken ct, ProfileJson profileJson) =>
|
|
{
|
|
var res = await repository.GetByIdAsync(profileJson._id, ct);
|
|
if (res == null)
|
|
{
|
|
res = new Profile();
|
|
res.MapFrom(profileJson);
|
|
foreach (var subscription in profileJson.subscriptions)
|
|
{
|
|
var sub = await subRepo.GetByIdAsync(subscription.id, ct);
|
|
if (sub == null)
|
|
{
|
|
sub = new Subscription();
|
|
sub.MapFrom(subscription);
|
|
await subRepo.AddAsync(sub, ct, false);
|
|
}
|
|
|
|
res.subscriptions.Add(sub);
|
|
}
|
|
await repository.AddAsync(res, ct);
|
|
}
|
|
else
|
|
{
|
|
res.MapFrom(profileJson);
|
|
var notFound = new List<Subscription>();
|
|
foreach (var subscription in res.subscriptions)
|
|
{
|
|
var f = profileJson.subscriptions.FirstOrDefault(s => s.id == subscription.id);
|
|
if (f == null)
|
|
notFound.Add(subscription);
|
|
else
|
|
{
|
|
subscription.MapFrom(f);
|
|
await subRepo.UpdateAsync(subscription, ct, false);
|
|
}
|
|
}
|
|
var newSubs = (from subscription in profileJson.subscriptions let f = res.subscriptions.FirstOrDefault(s => s.id == subscription.id) where f == null select subscription).ToList();
|
|
|
|
foreach (var newSub in newSubs)
|
|
{
|
|
var sres = await subRepo.GetByIdAsync(newSub.id, ct);
|
|
if (sres == null)
|
|
{
|
|
sres = new Subscription();
|
|
sres.MapFrom(newSub);
|
|
await subRepo.AddAsync(sres, ct, false);
|
|
}
|
|
|
|
res.subscriptions.Add(sres);
|
|
}
|
|
|
|
foreach (var nfSub in notFound)
|
|
{
|
|
res.subscriptions.Remove(nfSub);
|
|
}
|
|
|
|
await repository.UpdateAsync(res, ct);
|
|
}
|
|
|
|
return Results.Ok();
|
|
});
|
|
|
|
group.MapDelete("/{id}", async (IRepository<Profile> repository, CancellationToken ct, string id) =>
|
|
{
|
|
var result = await repository.GetByIdAsync(id, ct);
|
|
if (result == null) return Results.NotFound();
|
|
await repository.DeleteAsync(result, ct);
|
|
return Results.Ok();
|
|
});
|
|
}
|
|
} |