2025-08-08 16:59:29 -05:00
|
|
|
using FreeTubeSync.Model;
|
2025-07-19 04:02:09 -05:00
|
|
|
|
|
|
|
|
namespace FreeTubeSync.EndPoints;
|
|
|
|
|
|
|
|
|
|
public static class SettingEndpoint
|
|
|
|
|
{
|
|
|
|
|
public static void MapSettingEndpoints(this WebApplication app)
|
|
|
|
|
{
|
|
|
|
|
var group = app.MapGroup("settings");
|
|
|
|
|
|
2025-08-08 16:59:29 -05:00
|
|
|
group.MapGet("/", GetAllSettings);
|
|
|
|
|
group.MapGet("/{id}", GetSetting);
|
|
|
|
|
group.MapPost("/", UpdateSetting);
|
|
|
|
|
group.MapDelete("/{id}", DeleteSetting);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static async Task<IResult> GetAllSettings(IRepository<Setting> repository, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
var settings = await repository.GetAllAsync(ct);
|
|
|
|
|
return Results.Ok(settings);
|
|
|
|
|
}
|
2025-07-19 04:02:09 -05:00
|
|
|
|
2025-08-08 16:59:29 -05:00
|
|
|
private static async Task<IResult> GetSetting(IRepository<Setting> 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> UpdateSetting(IRepository<Setting> repository, Setting setting, CancellationToken ct, ILogger<Program> logger)
|
|
|
|
|
{
|
|
|
|
|
var res = await repository.GetByIdAsync(setting._id, ct);
|
|
|
|
|
if (res == null)
|
2025-07-19 04:02:09 -05:00
|
|
|
{
|
2025-08-08 16:59:29 -05:00
|
|
|
try
|
2025-07-22 17:03:33 -05:00
|
|
|
{
|
2025-08-09 04:09:17 -05:00
|
|
|
logger.LogInformation("Setting {id} does not exist, adding it to the database", setting._id);
|
2025-08-08 16:59:29 -05:00
|
|
|
await repository.AddAsync(setting, ct);
|
2025-07-22 17:03:33 -05:00
|
|
|
}
|
2025-08-09 04:09:17 -05:00
|
|
|
catch (Exception)
|
2025-07-21 17:10:42 -05:00
|
|
|
{
|
2025-08-09 04:09:17 -05:00
|
|
|
logger.LogError("Failed to add setting {setting}", setting._id);
|
2025-08-08 16:59:29 -05:00
|
|
|
return Results.StatusCode(500);
|
2025-07-21 17:10:42 -05:00
|
|
|
}
|
2025-08-08 16:59:29 -05:00
|
|
|
}
|
|
|
|
|
else
|
2025-07-19 04:02:09 -05:00
|
|
|
{
|
2025-08-09 04:09:17 -05:00
|
|
|
logger.LogInformation("Setting {id} exists, updating the database.", setting._id);
|
|
|
|
|
res.UpdateFrom(setting);
|
|
|
|
|
await repository.UpdateAsync(res, ct);
|
2025-08-08 16:59:29 -05:00
|
|
|
}
|
|
|
|
|
return Results.Ok();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static async Task<IResult> DeleteSetting(IRepository<Setting> 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();
|
2025-07-19 04:02:09 -05:00
|
|
|
}
|
|
|
|
|
}
|