< Summary

Information
Class: Elsa.Workflows.Api.Endpoints.WorkflowDefinitions.Post.Post
Assembly: Elsa.Workflows.Api
File(s): /home/runner/work/elsa-core/elsa-core/src/modules/Elsa.Workflows.Api/Endpoints/WorkflowDefinitions/Post/Endpoint.cs
Line coverage
17%
Covered lines: 10
Uncovered lines: 48
Coverable lines: 58
Total lines: 113
Line coverage: 17.2%
Branch coverage
0%
Covered branches: 0
Total branches: 38
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
Configure()100%11100%
HandleAsync()0%1482380%

File(s)

/home/runner/work/elsa-core/elsa-core/src/modules/Elsa.Workflows.Api/Endpoints/WorkflowDefinitions/Post/Endpoint.cs

#LineLine coverage
 1using System.Text.Json;
 2using Elsa.Abstractions;
 3using Elsa.Common.Models;
 4using Elsa.Workflows.Activities;
 5using Elsa.Workflows.Api.Constants;
 6using Elsa.Workflows.Api.Models;
 7using Elsa.Workflows.Api.Requirements;
 8using Elsa.Workflows.Management;
 9using Elsa.Workflows.Management.Mappers;
 10using Elsa.Workflows.Management.Materializers;
 11using Elsa.Workflows.Management.Models;
 12using Elsa.Workflows.Models;
 13using JetBrains.Annotations;
 14using Medallion.Threading;
 15using Microsoft.AspNetCore.Authorization;
 16using Microsoft.AspNetCore.Http;
 17
 18namespace Elsa.Workflows.Api.Endpoints.WorkflowDefinitions.Post;
 19
 20[PublicAPI]
 121internal class Post(
 122    IApiSerializer serializer,
 123    IWorkflowDefinitionPublisher workflowDefinitionPublisher,
 124    VariableDefinitionMapper variableDefinitionMapper,
 125    IDistributedLockProvider distributedLockProvider,
 126    IWorkflowDefinitionLinker linker,
 127    IAuthorizationService authorizationService)
 28    : ElsaEndpoint<SaveWorkflowDefinitionRequest, LinkedWorkflowDefinitionModel>
 29{
 30    public override void Configure()
 31    {
 132        Post("/workflow-definitions");
 133        ConfigurePermissions("write:workflow-definitions");
 134    }
 35
 36    public override async Task HandleAsync(SaveWorkflowDefinitionRequest request, CancellationToken cancellationToken)
 37    {
 038        var model = request.Model;
 039        var definitionId = model.DefinitionId;
 040        var resourceName = $"{GetType().FullName}:{(!string.IsNullOrWhiteSpace(definitionId) ? definitionId : Guid.NewGu
 41
 042        await using var handle = await distributedLockProvider.AcquireLockAsync(resourceName, TimeSpan.FromMinutes(1), c
 43
 044        var draft = !string.IsNullOrWhiteSpace(definitionId)
 045            ? await workflowDefinitionPublisher.GetDraftAsync(definitionId, VersionOptions.Latest, cancellationToken)
 046            : null;
 47
 048        var isNew = draft == null;
 49
 50        // Create a new workflow in case no existing definition was found.
 051        if (isNew)
 52        {
 053            draft = await workflowDefinitionPublisher.NewAsync(cancellationToken: cancellationToken);
 54
 055            if (!string.IsNullOrWhiteSpace(definitionId))
 056                draft.DefinitionId = definitionId;
 57        }
 58
 059        var authorizationResult = await authorizationService.AuthorizeAsync(User, new NotReadOnlyResource(draft), Author
 60
 061        if (!authorizationResult.Succeeded)
 62        {
 063            await Send.ForbiddenAsync(cancellationToken);
 064            return;
 65        }
 66
 67        // Update the draft with the received model.
 068        var root = model.Root ?? new Sequence();
 069        var serializerOptions = serializer.GetOptions();
 070        var stringData = JsonSerializer.Serialize(root, serializerOptions);
 071        var variables = variableDefinitionMapper.Map(model.Variables).ToList();
 072        var inputs = model.Inputs ?? new List<InputDefinition>();
 073        var outputs = model.Outputs ?? new List<OutputDefinition>();
 074        var outcomes = model.Outcomes ?? new List<string>();
 75
 076        draft!.StringData = stringData;
 077        draft.MaterializerName = JsonWorkflowMaterializer.MaterializerName;
 078        draft.Name = model.Name?.Trim();
 079        draft.ToolVersion = model.ToolVersion;
 080        draft.Description = model.Description?.Trim();
 081        draft.CustomProperties = model.CustomProperties ?? new Dictionary<string, object>();
 082        draft.Variables = variables;
 083        draft.Inputs = inputs;
 084        draft.Outputs = outputs;
 085        draft.Outcomes = outcomes;
 086        draft.Options = model.Options ?? new WorkflowOptions();
 87
 088        PublishWorkflowDefinitionResult? result = null;
 89
 090        if (request.Publish == true)
 91        {
 092            result = await workflowDefinitionPublisher.PublishAsync(draft, cancellationToken);
 93
 094            if (!result.Succeeded)
 95            {
 096                foreach (var validationError in result.ValidationErrors)
 097                    AddError(validationError.Message);
 98
 099                await Send.ErrorsAsync(400, cancellationToken);
 0100                return;
 101            }
 102        }
 103        else
 104        {
 0105            await workflowDefinitionPublisher.SaveDraftAsync(draft, cancellationToken);
 106        }
 107
 0108        var mappedDefinition = await linker.MapAsync(draft, cancellationToken);
 0109        var affectedWorkflows = result?.AffectedWorkflows?.WorkflowDefinitions ?? [];
 0110        var response = new Response(mappedDefinition, false, affectedWorkflows.Count);
 0111        await HttpContext.Response.WriteAsJsonAsync(response, serializerOptions, cancellationToken);
 0112    }
 113}