w4c-workflows-api/Services/Nodes/Executors/LimitNodeExecutor.cs
2026-09-12 01:02:46 +03:00

31 lines
1.1 KiB
C#

using w4c_workflows.Models.Nodes;
namespace w4c_workflows.Services.Nodes.Executors;
/// <summary>
/// Limit node. Keeps the first or last N items of the incoming batch and drops
/// the rest. Runs in all-items mode because "last N" needs the whole input.
/// </summary>
public sealed class LimitNodeExecutor : INodeExecutor
{
public string Type => "core.limit";
public Task<NodeExecutionOutcome> RunAsync(NodeExecutionContext context, CancellationToken ct)
{
var maxItems = NodeValueAccess.ReadInt(context.Parameters, "maxItems", 1);
if (maxItems < 0)
return Task.FromResult(NodeExecutionOutcome.Failed("maxItems must not be negative", "invalid_parameter"));
var items = context.Input(0);
var keep = NodeValueAccess.ReadString(context.Parameters, "keep") ?? "firstItems";
IReadOnlyList<FlowItem> output = keep switch
{
"lastItems" => items.Skip(Math.Max(0, items.Count - maxItems)).ToList(),
_ => items.Take(maxItems).ToList(),
};
return Task.FromResult(NodeExecutionOutcome.Single(output));
}
}