forked from FarmMaps/FarmMapsApiClient
Seperated eventhub service from api service.
wip nbs flow. Changed uploading a bit.
This commit is contained in:
45
FarmmapsApi/Services/FarmmapsEventHub.cs
Normal file
45
FarmmapsApi/Services/FarmmapsEventHub.cs
Normal file
@@ -0,0 +1,45 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using FarmmapsApi.Models;
|
||||
using Microsoft.AspNetCore.Http.Connections;
|
||||
using Microsoft.AspNetCore.SignalR.Client;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace FarmmapsApi.Services
|
||||
{
|
||||
public class FarmmapsEventHub
|
||||
{
|
||||
private readonly Configuration _configuration;
|
||||
private readonly HttpClientSettings _httpClientSettings;
|
||||
|
||||
private HubConnection _hubConnection;
|
||||
|
||||
public event Action<EventMessage> EventCallback;
|
||||
|
||||
public FarmmapsEventHub(HttpClientSettings httpClientSettings, Configuration configuration)
|
||||
{
|
||||
_httpClientSettings = httpClientSettings;
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
public async Task StartEventHub()
|
||||
{
|
||||
if(_hubConnection != null)
|
||||
throw new Exception("EventHub already started");
|
||||
|
||||
var eventEndpoint = $"{_configuration.Endpoint}/EventHub";
|
||||
_hubConnection = new HubConnectionBuilder()
|
||||
.WithUrl(eventEndpoint, HttpTransportType.WebSockets,
|
||||
options => options.SkipNegotiation = true)
|
||||
.ConfigureLogging(log => log.AddConsole())
|
||||
.WithAutomaticReconnect()
|
||||
.Build();
|
||||
|
||||
await _hubConnection.StartAsync();
|
||||
await _hubConnection.SendAsync("authenticate", _httpClientSettings.BearerToken);
|
||||
|
||||
_hubConnection.Reconnected += async s => await _hubConnection.SendAsync("authenticate", _httpClientSettings.BearerToken);
|
||||
_hubConnection.On("Event", (EventMessage eventMessage) => EventCallback?.Invoke(eventMessage));
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user