Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Created March 23, 2022 21:25
Show Gist options
  • Save dcomartin/7d969a0ee1324a8086b12f7443c6aaac to your computer and use it in GitHub Desktop.
Save dcomartin/7d969a0ee1324a8086b12f7443c6aaac to your computer and use it in GitHub Desktop.
namespace Webhooks.API.Services;
public class WebhooksSender : IWebhooksSender
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger _logger;
public WebhooksSender(IHttpClientFactory httpClientFactory, ILogger<WebhooksSender> logger)
{
_httpClientFactory = httpClientFactory;
_logger = logger;
}
public async Task SendAll(IEnumerable<WebhookSubscription> receivers, WebhookData data)
{
var client = _httpClientFactory.CreateClient();
var json = JsonSerializer.Serialize(data);
var tasks = receivers.Select(r => OnSendData(r, json, client));
await Task.WhenAll(tasks.ToArray());
}
private Task OnSendData(WebhookSubscription subs, string jsonData, HttpClient client)
{
var request = new HttpRequestMessage()
{
RequestUri = new Uri(subs.DestUrl, UriKind.Absolute),
Method = HttpMethod.Post,
Content = new StringContent(jsonData, Encoding.UTF8, "application/json")
};
if (!string.IsNullOrWhiteSpace(subs.Token))
{
request.Headers.Add("X-eshop-whtoken", subs.Token);
}
_logger.LogDebug("Sending hook to {DestUrl} of type {Type}", subs.Type.ToString(), subs.Type.ToString());
return client.SendAsync(request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment