61 lines
2.2 KiB
C#
61 lines
2.2 KiB
C#
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Runtime.CompilerServices;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using RudderSdk.Core.Models.Storage;
|
|
|
|
namespace RudderSdk.Core;
|
|
|
|
/// <summary>Player key-value storage.</summary>
|
|
public sealed class StorageService
|
|
{
|
|
private readonly RudderClient _client;
|
|
|
|
internal StorageService(RudderClient client) => _client = client;
|
|
|
|
/// <summary>Fetches one page of storage items, optionally filtered by type.</summary>
|
|
public Task<GetStorageResponse> GetAsync(string? type = null, int limit = 100, string? cursor = null, CancellationToken cancellationToken = default)
|
|
{
|
|
var query = Url.Query(
|
|
("types", type),
|
|
("limit", limit > 0 ? limit.ToString() : null),
|
|
("cursor", cursor));
|
|
|
|
return _client.SendAsync<GetStorageResponse>("GET", "/sdk/v1/storage" + query, cancellationToken);
|
|
}
|
|
|
|
/// <summary>Iterates over all storage items, following the cursor pagination.</summary>
|
|
public async IAsyncEnumerable<StorageItem> ListAllAsync(
|
|
string? type = null,
|
|
int limit = 100,
|
|
[EnumeratorCancellation] CancellationToken cancellationToken = default)
|
|
{
|
|
string? cursor = null;
|
|
do
|
|
{
|
|
var page = await GetAsync(type, limit, cursor, cancellationToken).ConfigureAwait(false);
|
|
if (page?.Items != null)
|
|
{
|
|
foreach (var item in page.Items)
|
|
yield return item;
|
|
}
|
|
|
|
cursor = page?.NextCursor;
|
|
}
|
|
while (!string.IsNullOrEmpty(cursor));
|
|
}
|
|
|
|
/// <summary>Saves (upserts) storage items.</summary>
|
|
public Task SaveAsync(IEnumerable<StorageItem> items, CancellationToken cancellationToken = default)
|
|
=> _client.SendAsync(
|
|
"PUT",
|
|
"/sdk/v1/storage",
|
|
new UpdateStorageRequest { Items = items?.ToList() ?? new List<StorageItem>() },
|
|
cancellationToken);
|
|
|
|
/// <summary>Deletes all items of the given type.</summary>
|
|
public Task DeleteAsync(string type, CancellationToken cancellationToken = default)
|
|
=> _client.SendAsync("DELETE", "/sdk/v1/storage" + Url.Query(("type", type)), cancellationToken);
|
|
}
|