Files
rudder-csharp-sdk/Services/Effects/StoreOfferEffect.cs
T

75 lines
2.4 KiB
C#
Raw Normal View History

using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace RudderSdk.Core;
/// <summary>A scenario store-offer node. Resolve it with <see cref="PurchaseAsync"/> or <see cref="DeclineAsync"/>.</summary>
public sealed class StoreOfferEffect
{
private readonly EffectHandle _handle;
internal StoreOfferEffect(EffectHandle handle) => _handle = handle;
/// <summary>Run id.</summary>
public string RunId => _handle.RunId;
/// <summary>Scenario id.</summary>
public string ScenarioSlug => _handle.ScenarioSlug;
/// <summary>Node id.</summary>
public string NodeId => _handle.NodeId;
/// <summary>Store slug from the node data, if present.</summary>
public string StoreSlug => _handle.Get("storeSlug", string.Empty);
/// <summary>Optional message from the node data.</summary>
public string? Message
{
get
{
var value = _handle.Get<string?>("message", null);
return string.IsNullOrEmpty(value) ? null : value;
}
}
/// <summary>Node data payload.</summary>
public JObject Data => _handle.Data;
/// <summary>True after the offer was resolved once.</summary>
public bool IsResolved { get; private set; }
/// <summary>Reads a typed value from the node data.</summary>
public T Get<T>(string key, T defaultValue = default!) => _handle.Get(key, defaultValue);
/// <summary>Posts the <c>onPurchase</c> callback.</summary>
public Task PurchaseAsync(CancellationToken cancellationToken = default) => ResolveAsync("onPurchase", cancellationToken);
/// <summary>Posts the <c>onPurchase</c> callback (fire-and-forget).</summary>
public void Purchase() => Resolve("onPurchase");
/// <summary>Posts the <c>onDecline</c> callback.</summary>
public Task DeclineAsync(CancellationToken cancellationToken = default) => ResolveAsync("onDecline", cancellationToken);
/// <summary>Posts the <c>onDecline</c> callback (fire-and-forget).</summary>
public void Decline() => Resolve("onDecline");
private async Task ResolveAsync(string handle, CancellationToken cancellationToken)
{
if (IsResolved)
return;
IsResolved = true;
await _handle.CompleteAsync(handle, cancellationToken).ConfigureAwait(false);
}
private void Resolve(string handle)
{
if (IsResolved)
return;
IsResolved = true;
_handle.Complete(handle);
}
}