| | | 1 | | using Estud.Back.Domain.Webhooks; |
| | | 2 | | |
| | | 3 | | namespace Estud.Back.Features.Webhooks.UpdateWebhookSubscription; |
| | | 4 | | |
| | 16 | 5 | | public class UpdateWebhookSubscriptionService(EstudDbContext ctx) : IEstudService |
| | | 6 | | { |
| | | 7 | | private class Validator : AbstractValidator<UpdateWebhookSubscriptionIn> |
| | | 8 | | { |
| | 2 | 9 | | public Validator() |
| | | 10 | | { |
| | 2 | 11 | | RuleFor(x => x.Name).NotEmpty().WithError(InvalidWebhookName.I); |
| | 2 | 12 | | RuleFor(x => x.Name).MaximumLength(100).WithError(InvalidWebhookName.I); |
| | | 13 | | |
| | 2 | 14 | | RuleFor(x => x.Url).NotEmpty().WithError(InvalidWebhookUrl.I); |
| | 18 | 15 | | RuleFor(x => x.Url).Must(x => Uri.TryCreate(x, UriKind.Absolute, out _)).WithError(InvalidWebhookUrl.I); |
| | | 16 | | |
| | 18 | 17 | | RuleFor(x => x.Events).Must(x => x != null && x.Count > 0).WithError(InvalidWebhookEvents.I); |
| | | 18 | | |
| | 2 | 19 | | RuleFor(x => x.CustomHeaders).Must(WebhookCustomHeaders.IsValid).WithError(InvalidWebhookCustomHeaders.I); |
| | 2 | 20 | | } |
| | | 21 | | } |
| | 2 | 22 | | private static readonly Validator V = new(); |
| | | 23 | | |
| | | 24 | | public async Task<OneOf<UpdateWebhookSubscriptionOut, EstudError>> Update(UpdateWebhookSubscriptionIn data) |
| | | 25 | | { |
| | 28 | 26 | | if (V.Run(data, out var error)) return error; |
| | | 27 | | |
| | 4 | 28 | | var subscription = await ctx.WebhookSubscriptions |
| | 4 | 29 | | .FirstOrDefaultAsync(x => x.InstitutionId == ctx.RequestUser.InstitutionId && x.Id == data.Id); |
| | 6 | 30 | | if (subscription == null) return WebhookSubscriptionNotFound.I; |
| | | 31 | | |
| | 2 | 32 | | subscription.Update(data.Name, data.Url, data.Events, data.CustomHeaders, data.IsActive); |
| | 2 | 33 | | await ctx.SaveChangesAsync(); |
| | | 34 | | |
| | 2 | 35 | | return new UpdateWebhookSubscriptionOut { Id = subscription.Id }; |
| | 16 | 36 | | } |
| | | 37 | | } |