| | | 1 | | using System.Text; |
| | | 2 | | |
| | | 3 | | namespace Estud.Back.Features.Webhooks.CallWebhooks; |
| | | 4 | | |
| | | 5 | | [CommandDescription("Chama um webhook")] |
| | | 6 | | public record CallWebhookCommand(int WebhookCallId) : ICommand; |
| | | 7 | | |
| | 18 | 8 | | public class CallWebhookCommandHandler(EstudDbContext ctx, IHttpClientFactory factory) : ICommandHandler<CallWebhookComm |
| | | 9 | | { |
| | | 10 | | public async Task Handle(int commandId, CallWebhookCommand command) |
| | | 11 | | { |
| | 18 | 12 | | var call = await ctx.WebhookCalls |
| | 18 | 13 | | .Include(x => x.Attempts) |
| | 18 | 14 | | .FirstOrDefaultAsync(x => x.Id == command.WebhookCallId); |
| | | 15 | | |
| | 18 | 16 | | var webhook = await ctx.WebhookSubscriptions.AsNoTracking() |
| | 18 | 17 | | .Where(x => x.Id == call.WebhookSubscriptionId) |
| | 18 | 18 | | .Select(x => new { x.Url, x.CustomHeaders }) |
| | 18 | 19 | | .FirstAsync(); |
| | | 20 | | |
| | 18 | 21 | | var client = factory.CreateClient(); |
| | 18 | 22 | | client.BaseAddress = new Uri(webhook.Url); |
| | 44 | 23 | | foreach (var header in webhook.CustomHeaders) |
| | | 24 | | { |
| | 4 | 25 | | client.DefaultRequestHeaders.Add(header.Key, header.Value); |
| | | 26 | | } |
| | | 27 | | |
| | | 28 | | try |
| | | 29 | | { |
| | 18 | 30 | | var payload = new StringContent(call.Payload, Encoding.UTF8, "application/json"); |
| | 18 | 31 | | var response = await client.PostAsync("", payload); |
| | 18 | 32 | | var responseContent = await response.Content.ReadAsStringAsync(); |
| | | 33 | | |
| | 18 | 34 | | if (response.IsSuccessStatusCode) |
| | | 35 | | { |
| | 16 | 36 | | call.Success((int)response.StatusCode, responseContent); |
| | | 37 | | } |
| | | 38 | | else |
| | | 39 | | { |
| | 2 | 40 | | call.Failed((int)response.StatusCode, responseContent); |
| | | 41 | | } |
| | 18 | 42 | | } |
| | 0 | 43 | | catch (Exception ex) |
| | | 44 | | { |
| | 0 | 45 | | call.Failed(999, ex.Message); |
| | 0 | 46 | | } |
| | 18 | 47 | | } |
| | | 48 | | } |