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