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