2022-04-07 10:44:12 +00:00
|
|
|
|
using System.Text.Json.Serialization;
|
2022-05-26 10:47:31 +00:00
|
|
|
|
using Elsa.Workflows.Core.Attributes;
|
|
|
|
|
|
using Elsa.Workflows.Core.Models;
|
|
|
|
|
|
using IJavaScriptEvaluator = Elsa.JavaScript.Services.IJavaScriptEvaluator;
|
2022-03-07 14:42:12 +00:00
|
|
|
|
|
2022-05-26 10:47:31 +00:00
|
|
|
|
namespace Elsa.JavaScript.Activities;
|
2022-03-07 14:42:12 +00:00
|
|
|
|
|
2022-05-10 12:27:23 +00:00
|
|
|
|
[Activity("Elsa", "Scripting", "Executes JavaScript code")]
|
2022-04-07 10:44:12 +00:00
|
|
|
|
public class RunJavaScript : Activity<object?>
|
2022-03-07 14:42:12 +00:00
|
|
|
|
{
|
2022-04-07 10:44:12 +00:00
|
|
|
|
[JsonConstructor]
|
2022-03-07 14:42:12 +00:00
|
|
|
|
public RunJavaScript()
|
|
|
|
|
|
{
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public RunJavaScript(string script)
|
|
|
|
|
|
{
|
|
|
|
|
|
Script = new Input<string>(script);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public Input<string> Script { get; set; } = new("");
|
|
|
|
|
|
|
|
|
|
|
|
protected override async ValueTask ExecuteAsync(ActivityExecutionContext context)
|
|
|
|
|
|
{
|
|
|
|
|
|
var script = context.Get(Script);
|
|
|
|
|
|
|
|
|
|
|
|
// If no script was specified, there's nothing to do.
|
|
|
|
|
|
if (string.IsNullOrWhiteSpace(script))
|
|
|
|
|
|
return;
|
|
|
|
|
|
|
|
|
|
|
|
// Get a JavaScript evaluator.
|
|
|
|
|
|
var javaScriptEvaluator = context.GetRequiredService<IJavaScriptEvaluator>();
|
|
|
|
|
|
|
|
|
|
|
|
// Run the script.
|
|
|
|
|
|
var result = await javaScriptEvaluator.EvaluateAsync(script, typeof(object), context.ExpressionExecutionContext, cancellationToken: context.CancellationToken);
|
|
|
|
|
|
|
|
|
|
|
|
// Set the result as output, if any.
|
|
|
|
|
|
context.Set(Result, result);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|