| | | 1 | | using System.Text.Json; |
| | | 2 | | using Elsa.Abstractions; |
| | | 3 | | using Elsa.Workflows.Management; |
| | | 4 | | using Elsa.Workflows.Runtime; |
| | | 5 | | using JetBrains.Annotations; |
| | | 6 | | |
| | | 7 | | namespace Elsa.Workflows.Api.Endpoints.WorkflowDefinitions.Execute; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// An API endpoint that executes a given workflow definition through POST method. |
| | | 11 | | /// </summary> |
| | | 12 | | [PublicAPI] |
| | 10 | 13 | | internal class PostEndpoint( |
| | 10 | 14 | | IWorkflowDefinitionService workflowDefinitionService, |
| | 10 | 15 | | IWorkflowRuntime workflowRuntime, |
| | 10 | 16 | | IWorkflowStarter workflowStarter, |
| | 10 | 17 | | IApiSerializer apiSerializer) |
| | | 18 | | : ElsaEndpointWithoutRequest<Response> |
| | | 19 | | { |
| | | 20 | | /// <inheritdoc /> |
| | | 21 | | public override void Configure() |
| | | 22 | | { |
| | 1 | 23 | | Routes("/workflow-definitions/{definitionId}/execute"); |
| | 1 | 24 | | ConfigurePermissions("exec:workflow-definitions"); |
| | 1 | 25 | | Verbs(FastEndpoints.Http.POST); |
| | 1 | 26 | | } |
| | | 27 | | /// <inheritdoc /> |
| | | 28 | | public override async Task HandleAsync(CancellationToken cancellationToken) |
| | | 29 | | { |
| | 9 | 30 | | PostRequest? request = null; |
| | | 31 | | |
| | 9 | 32 | | if (HttpContext.Request.ContentType?.Contains("application/json") ?? false) |
| | | 33 | | { |
| | 8 | 34 | | using var reader = new StreamReader(HttpContext.Request.Body); |
| | 8 | 35 | | var body = await reader.ReadToEndAsync(); |
| | | 36 | | |
| | 8 | 37 | | if (!string.IsNullOrWhiteSpace(body)) |
| | | 38 | | { |
| | | 39 | | try |
| | | 40 | | { |
| | 7 | 41 | | request = JsonSerializer.Deserialize<PostRequest>(body, new JsonSerializerOptions |
| | 7 | 42 | | { |
| | 7 | 43 | | PropertyNameCaseInsensitive = true |
| | 7 | 44 | | }); |
| | 7 | 45 | | } |
| | 0 | 46 | | catch |
| | | 47 | | { |
| | 0 | 48 | | AddError("Invalid request body."); |
| | 0 | 49 | | } |
| | | 50 | | } |
| | 8 | 51 | | } |
| | | 52 | | |
| | 9 | 53 | | request ??= new(); |
| | | 54 | | |
| | 9 | 55 | | var definitionId = Route<string>("definitionId"); |
| | | 56 | | |
| | 9 | 57 | | if (string.IsNullOrWhiteSpace(definitionId)) |
| | 0 | 58 | | AddError("Missing workflow definition ID."); |
| | | 59 | | else |
| | 9 | 60 | | request.DefinitionId = definitionId; |
| | | 61 | | |
| | 9 | 62 | | if (ValidationFailed) |
| | | 63 | | { |
| | 0 | 64 | | await Send.ErrorsAsync(cancellation: cancellationToken); |
| | 0 | 65 | | return; |
| | | 66 | | } |
| | | 67 | | |
| | 9 | 68 | | await WorkflowExecutionHelper.ExecuteWorkflowAsync( |
| | 9 | 69 | | request, |
| | 9 | 70 | | workflowDefinitionService, |
| | 9 | 71 | | workflowRuntime, |
| | 9 | 72 | | workflowStarter, |
| | 9 | 73 | | apiSerializer, |
| | 9 | 74 | | HttpContext, |
| | 9 | 75 | | cancellationToken); |
| | 9 | 76 | | } |
| | | 77 | | } |