using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace ReC.Client.Api
{
///
/// Provides shared CRUD operations for API resources.
///
public abstract class BaseCrudApi
{
///
/// The HTTP client used to send requests.
///
protected readonly HttpClient Http;
///
/// The base resource path for the API endpoint.
///
protected readonly string ResourcePath;
///
/// Initializes a new instance of the class.
///
/// The HTTP client used for requests.
/// The base resource path for the API endpoint.
protected BaseCrudApi(HttpClient http, string resourcePath)
{
Http = http ?? throw new ArgumentNullException(nameof(http));
ResourcePath = resourcePath ?? throw new ArgumentNullException(nameof(resourcePath));
}
///
/// Creates a resource.
///
/// The payload type.
/// The payload to send.
/// A token to cancel the operation.
/// The HTTP response message.
public Task CreateAsync(T payload, CancellationToken cancel = default)
=> Http.PostAsync(ResourcePath, ReCClientHelpers.ToJsonContent(payload), cancel);
///
/// Updates a resource by identifier.
///
/// The payload type.
/// The resource identifier.
/// The payload to send.
/// A token to cancel the operation.
/// The HTTP response message.
public Task UpdateAsync(long id, T payload, CancellationToken cancel = default)
=> Http.PutAsync($"{ResourcePath}/{id}", ReCClientHelpers.ToJsonContent(payload), cancel);
///
/// Deletes resources with identifiers supplied in the payload.
///
/// The payload type containing identifiers.
/// The payload to send.
/// A token to cancel the operation.
/// The HTTP response message.
public Task DeleteAsync(T payload, CancellationToken cancel = default)
{
var request = new HttpRequestMessage(HttpMethod.Delete, ResourcePath)
{
Content = ReCClientHelpers.ToJsonContent(payload)
};
return Http.SendAsync(request, cancel);
}
}
}