Beispiel #1
0
    public bool GenerateCode()
    {
        var resultTypeName = ApiOperation.GetOperationName() + NameConstants.ContractResult;

        // Create compilationUnit
        var compilationUnit = SyntaxFactory.CompilationUnit();

        // Create a namespace
        var @namespace = SyntaxProjectFactory.CreateNamespace(
            ApiProjectOptions,
            NameConstants.Contracts,
            FocusOnSegmentName);

        // Create class
        var classDeclaration = SyntaxClassDeclarationFactory.CreateWithInheritClassType(resultTypeName, "ResultBase")
                               .AddGeneratedCodeAttribute(ApiProjectOptions.ToolName, ApiProjectOptions.ToolVersion.ToString())
                               .WithLeadingTrivia(SyntaxDocumentationFactory.CreateForResults(ApiOperation, FocusOnSegmentName));

        // Create members
        var memberDeclarations = CreateMembers(resultTypeName);

        // Add members to class
        classDeclaration = memberDeclarations.Aggregate(
            classDeclaration,
            (current, memberDeclaration) => current.AddMembers(memberDeclaration));

        // Add using statement to compilationUnit
        compilationUnit = compilationUnit.AddUsingStatements(
            ProjectApiFactory.CreateUsingListForContractResult(
                ApiOperation.Responses,
                ApiProjectOptions.ApiOptions.Generator.Response.UseProblemDetailsAsDefaultBody,
                HasCreateContentResult));

        // Add the class to the namespace.
        @namespace = @namespace.AddMembers(classDeclaration);

        // Add namespace to compilationUnit
        compilationUnit = compilationUnit.AddMembers(@namespace);

        // Set code property
        Code = compilationUnit;
        return(true);
    }
    public bool GenerateCode()
    {
        var interfaceTypeName = "I" + ApiOperation.GetOperationName() + NameConstants.ContractHandler;
        var parameterTypeName = ApiOperation.GetOperationName() + NameConstants.ContractParameters;
        var resultTypeName    = ApiOperation.GetOperationName() + NameConstants.ContractResult;

        // Create compilationUnit
        var compilationUnit = SyntaxFactory.CompilationUnit();

        // Create a namespace
        var @namespace = SyntaxProjectFactory.CreateNamespace(
            ApiProjectOptions,
            NameConstants.Contracts,
            FocusOnSegmentName);

        // Create interface
        var interfaceDeclaration = SyntaxInterfaceDeclarationFactory.Create(interfaceTypeName)
                                   .AddGeneratedCodeAttribute(ApiProjectOptions.ToolName, ApiProjectOptions.ToolVersion.ToString())
                                   .WithLeadingTrivia(SyntaxDocumentationFactory.CreateForInterface(ApiOperation, FocusOnSegmentName));

        // Create interface-method
        var methodDeclaration = SyntaxMethodDeclarationFactory.CreateInterfaceMethod(parameterTypeName, resultTypeName, HasParametersOrRequestBody)
                                .WithLeadingTrivia(SyntaxDocumentationFactory.CreateForInterfaceMethod(GlobalPathParameters.Any() || ApiOperation.HasParametersOrRequestBody()));

        // Add using statement to compilationUnit
        compilationUnit = compilationUnit.AddUsingStatements(ProjectApiFactory.CreateUsingListForContractInterface());

        // Add interface-method to interface
        interfaceDeclaration = interfaceDeclaration.AddMembers(methodDeclaration);

        // Add the interface to the namespace.
        @namespace = @namespace.AddMembers(interfaceDeclaration);

        // Add namespace to compilationUnit
        compilationUnit = compilationUnit.AddMembers(@namespace);

        // Set code property
        Code = compilationUnit;
        return(true);
    }
Beispiel #3
0
    public bool GenerateCode()
    {
        var parameterTypeName = ApiOperation.GetOperationName() + NameConstants.ContractParameters;

        // Create compilationUnit
        var compilationUnit = SyntaxFactory.CompilationUnit();

        // Create a namespace
        var @namespace = SyntaxProjectFactory.CreateNamespace(
            ApiProjectOptions,
            NameConstants.Contracts,
            FocusOnSegmentName);

        // Create class
        var classDeclaration = SyntaxClassDeclarationFactory.Create(parameterTypeName)
                               .AddGeneratedCodeAttribute(ApiProjectOptions.ToolName, ApiProjectOptions.ToolVersion.ToString())
                               .WithLeadingTrivia(SyntaxDocumentationFactory.CreateForParameters(ApiOperation, FocusOnSegmentName));

        // Add properties to the class
        if (GlobalPathParameters.Any())
        {
            foreach (var parameter in GlobalPathParameters)
            {
                var propertyDeclaration = SyntaxPropertyDeclarationFactory.CreateAuto(
                    parameter,
                    ApiProjectOptions.UseNullableReferenceTypes,
                    ApiProjectOptions.IsForClient)
                                          .WithLeadingTrivia(SyntaxDocumentationFactory.CreateForParameter(parameter));
                classDeclaration = classDeclaration.AddMembers(propertyDeclaration);
            }
        }

        if (ApiOperation.Parameters is not null)
        {
            foreach (var parameter in ApiOperation.Parameters)
            {
                var propertyDeclaration = SyntaxPropertyDeclarationFactory.CreateAuto(
                    parameter,
                    ApiProjectOptions.UseNullableReferenceTypes,
                    ApiProjectOptions.IsForClient)
                                          .WithLeadingTrivia(SyntaxDocumentationFactory.CreateForParameter(parameter));
                classDeclaration = classDeclaration.AddMembers(propertyDeclaration);
            }
        }

        var requestSchema = ApiOperation.RequestBody?.Content?.GetSchemaByFirstMediaType();

        if (ApiOperation.RequestBody is not null &&
            requestSchema is not null)
        {
            var isFormatTypeOfBinary      = requestSchema.IsFormatTypeBinary();
            var isItemsOfFormatTypeBinary = requestSchema.HasItemsWithFormatTypeBinary();

            var requestBodyType = "string?";
            if (requestSchema.Reference is not null)
            {
                requestBodyType = requestSchema.Reference.Id.EnsureFirstCharacterToUpper();
            }
            else if (isFormatTypeOfBinary)
            {
                requestBodyType = "IFormFile";
            }
            else if (isItemsOfFormatTypeBinary)
            {
                requestBodyType = "IFormFile";
            }
            else if (requestSchema.Items is not null)
            {
                requestBodyType = requestSchema.Items.Reference.Id.EnsureFirstCharacterToUpper();
            }

            PropertyDeclarationSyntax propertyDeclaration;
            if (requestSchema.IsTypeArray())
            {
                if (ApiProjectOptions.IsForClient)
                {
                    propertyDeclaration = SyntaxPropertyDeclarationFactory.CreateListAuto(requestBodyType, NameConstants.Request)
                                          .AddValidationAttribute(new RequiredAttribute())
                                          .WithLeadingTrivia(SyntaxDocumentationFactory.CreateForParameter(ApiOperation.RequestBody));
                }
                else
                {
                    propertyDeclaration = SyntaxPropertyDeclarationFactory.CreateListAuto(requestBodyType, NameConstants.Request);

                    propertyDeclaration = requestSchema.HasItemsWithFormatTypeBinary()
                        ? propertyDeclaration.AddFromFormAttribute()
                        : propertyDeclaration.AddFromBodyAttribute();

                    propertyDeclaration = propertyDeclaration
                                          .AddValidationAttribute(new RequiredAttribute())
                                          .WithLeadingTrivia(SyntaxDocumentationFactory.CreateForParameter(ApiOperation.RequestBody));
                }
            }
            else
            {
                if (ApiProjectOptions.IsForClient)
                {
                    propertyDeclaration = SyntaxPropertyDeclarationFactory.CreateAuto(
                        parameterLocation: null,
                        isNullable: false,
                        isRequired: true,
                        requestBodyType,
                        NameConstants.Request,
                        ApiProjectOptions.UseNullableReferenceTypes,
                        initializer: null)
                                          .AddValidationAttribute(new RequiredAttribute())
                                          .WithLeadingTrivia(SyntaxDocumentationFactory.CreateForParameter(ApiOperation.RequestBody));
                }
                else
                {
                    propertyDeclaration = SyntaxPropertyDeclarationFactory.CreateAuto(
                        parameterLocation: null,
                        isNullable: false,
                        isRequired: true,
                        requestBodyType,
                        NameConstants.Request,
                        ApiProjectOptions.UseNullableReferenceTypes,
                        initializer: null);

                    propertyDeclaration = requestSchema.HasAnyPropertiesWithFormatTypeBinary() || requestSchema.HasAnyPropertiesAsArrayWithFormatTypeBinary()
                        ? propertyDeclaration.AddFromFormAttribute()
                        : propertyDeclaration.AddFromBodyAttribute();

                    propertyDeclaration = propertyDeclaration
                                          .AddValidationAttribute(new RequiredAttribute())
                                          .WithLeadingTrivia(SyntaxDocumentationFactory.CreateForParameter(ApiOperation.RequestBody));
                }
            }

            classDeclaration = classDeclaration.AddMembers(propertyDeclaration);
        }

        var methodDeclaration = SyntaxMethodDeclarationFactory.CreateToStringMethod(GlobalPathParameters, ApiOperation.Parameters, ApiOperation.RequestBody);

        if (methodDeclaration is not null)
        {
            methodDeclaration = methodDeclaration.WithLeadingTrivia(SyntaxDocumentationFactory.CreateForOverrideToString());
            classDeclaration  = classDeclaration.AddMembers(methodDeclaration);
        }

        // Add using statement to compilationUnit
        compilationUnit = compilationUnit.AddUsingStatements(
            ProjectApiFactory.CreateUsingListForContractParameter(
                GlobalPathParameters,
                ApiOperation.Parameters,
                ApiOperation.RequestBody,
                ApiProjectOptions.IsForClient));

        // Add the class to the namespace.
        @namespace = @namespace.AddMembers(classDeclaration);

        // Add namespace to compilationUnit
        compilationUnit = compilationUnit.AddMembers(@namespace);

        // Set code property
        Code = compilationUnit;
        return(true);
    }
Beispiel #4
0
    public bool GenerateCode()
    {
        var controllerTypeName = FocusOnSegmentName.EnsureFirstCharacterToUpper() + "Controller";

        // Create compilationUnit
        var compilationUnit = SyntaxFactory.CompilationUnit();

        // Create a namespace
        var @namespace = SyntaxProjectFactory.CreateNamespace(
            ApiProjectOptions,
            NameConstants.Endpoints);

        // Create class
        var classDeclaration = SyntaxClassDeclarationFactory.Create(controllerTypeName);

        if (ApiProjectOptions.ApiOptions.Generator.UseAuthorization)
        {
            classDeclaration =
                classDeclaration.AddAttributeLists(
                    SyntaxAttributeListFactory.Create(nameof(AuthorizeAttribute)));
        }

        classDeclaration = classDeclaration.AddAttributeLists(
            SyntaxAttributeListFactory.Create(nameof(ApiControllerAttribute)),
            SyntaxAttributeListFactory.CreateWithOneItemWithOneArgument(nameof(RouteAttribute), $"{ApiProjectOptions.RouteBase}/{GetRouteSegment()}"))
                           .AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName(nameof(ControllerBase))))
                           .AddGeneratedCodeAttribute(ApiProjectOptions.ToolName, ApiProjectOptions.ToolVersion.ToString())
                           .WithLeadingTrivia(SyntaxDocumentationFactory.CreateForEndpoints(FocusOnSegmentName));

        // Create Methods
        var usedApiOperations = new List <OpenApiOperation>();

        foreach (var(key, value) in ApiProjectOptions.Document.GetPathsByBasePathSegmentName(FocusOnSegmentName))
        {
            var hasRouteParameters = value.HasParameters();
            foreach (var apiOperation in value.Operations)
            {
                var methodDeclaration = CreateMembersForEndpoints(apiOperation, key, FocusOnSegmentName, hasRouteParameters)
                                        .WithLeadingTrivia(SyntaxDocumentationFactory.CreateForEndpointMethods(apiOperation, FocusOnSegmentName));
                classDeclaration = classDeclaration.AddMembers(methodDeclaration);

                usedApiOperations.Add(apiOperation.Value);
            }
        }

        // Create private part for methods
        foreach (var(_, value) in ApiProjectOptions.Document.GetPathsByBasePathSegmentName(FocusOnSegmentName))
        {
            var hasRouteParameters = value.HasParameters();
            foreach (var apiOperation in value.Operations)
            {
                var methodDeclaration = CreateMembersForEndpointsPrivateHelper(apiOperation, hasRouteParameters);
                classDeclaration = classDeclaration.AddMembers(methodDeclaration);

                usedApiOperations.Add(apiOperation.Value);
            }
        }

        // Add the class to the namespace.
        @namespace = @namespace.AddMembers(classDeclaration);

        // Add using statement to compilationUnit
        var includeRestResults = classDeclaration
                                 .Select <IdentifierNameSyntax>()
                                 .Any(x => x.Identifier.ValueText.Contains($"({Microsoft.OpenApi.Models.NameConstants.Pagination}<", StringComparison.Ordinal));

        compilationUnit = compilationUnit.AddUsingStatements(
            ProjectApiFactory.CreateUsingListForEndpoint(
                ApiProjectOptions,
                usedApiOperations,
                HasSharedResponseContract(),
                includeRestResults,
                FocusOnSegmentName));

        // Add namespace to compilationUnit
        compilationUnit = compilationUnit.AddMembers(@namespace);

        // Set code property
        Code = compilationUnit;
        return(true);
    }
Beispiel #5
0
    private NamespaceDeclarationSyntax GenerateCodeForOtherThanEnum(
        ref CompilationUnitSyntax?compilationUnit)
    {
        // Create a namespace
        var @namespace = IsSharedContract
            ? SyntaxProjectFactory.CreateNamespace(ApiProjectOptions, NameConstants.Contracts)
            : SyntaxProjectFactory.CreateNamespace(ApiProjectOptions, NameConstants.Contracts, FocusOnSegmentName);

        // Create class
        var classDeclaration = SyntaxClassDeclarationFactory.Create(ApiSchemaKey.EnsureFirstCharacterToUpper())
                               .AddGeneratedCodeAttribute(ApiProjectOptions.ToolName, ApiProjectOptions.ToolVersion.ToString())
                               .WithLeadingTrivia(SyntaxDocumentationFactory.Create(ApiSchema));

        var hasAnyPropertiesAsArrayWithFormatTypeBinary = ApiSchema.HasAnyPropertiesAsArrayWithFormatTypeBinary();

        // Create class-properties and add to class
        if (ApiSchema.Properties is not null)
        {
            if (ApiSchema.IsTypeArray() ||
                hasAnyPropertiesAsArrayWithFormatTypeBinary)
            {
                var(key, _) = ApiProjectOptions.Document.Components.Schemas.FirstOrDefault(x =>
                                                                                           x.Key.Equals(ApiSchema.Title, StringComparison.OrdinalIgnoreCase));
                if (string.IsNullOrEmpty(ApiSchema.Title))
                {
                    ApiSchema.Title = ApiSchemaKey;
                    key             = ApiSchemaKey;
                }

                if (ApiSchema.Items is not null &&
                    string.IsNullOrEmpty(ApiSchema.Items.Title))
                {
                    ApiSchema.Items.Title = ApiSchemaKey;
                }

                var title = key is not null
                    ? $"{ApiSchema.Title.EnsureFirstCharacterToUpperAndSingular()}List"
                    : ApiSchema.Title.EnsureFirstCharacterToUpper();

                var propertyDeclaration = hasAnyPropertiesAsArrayWithFormatTypeBinary
                    ? SyntaxPropertyDeclarationFactory.CreateListAuto("IFormFile", ApiSchema.ExtractPropertyNameWhenHasAnyPropertiesOfArrayWithFormatTypeBinary())
                                          .WithLeadingTrivia(
                    SyntaxDocumentationFactory.CreateSummary("A list of File(s)."))
                    : SyntaxPropertyDeclarationFactory.CreateListAuto(ApiSchema.Items !.Title, title)
                                          .WithLeadingTrivia(
                    SyntaxDocumentationFactory.CreateSummary($"A list of {ApiSchema.Items.Title}."));

                classDeclaration = classDeclaration.AddMembers(propertyDeclaration);
            }
            else
            {
                foreach (var property in ApiSchema.Properties)
                {
                    var propertyDeclaration = SyntaxPropertyDeclarationFactory.CreateAuto(
                        property,
                        ApiSchema.Required,
                        ApiProjectOptions.UseNullableReferenceTypes)
                                              .WithLeadingTrivia(SyntaxDocumentationFactory.Create(property.Value));
                    classDeclaration = classDeclaration.AddMembers(propertyDeclaration);
                }
            }

            var methodDeclaration = SyntaxMethodDeclarationFactory.CreateToStringMethod(ApiSchema.Properties);
            if (methodDeclaration is not null)
            {
                methodDeclaration = methodDeclaration.WithLeadingTrivia(SyntaxDocumentationFactory.CreateForOverrideToString());
                classDeclaration  = classDeclaration.AddMembers(methodDeclaration);
            }
        }

        // Add using statement to compilationUnit
        compilationUnit = compilationUnit !.AddUsingStatements(ProjectApiFactory.CreateUsingListForContractModel(ApiSchema));

        // Add the class to the namespace.
        @namespace = @namespace.AddMembers(classDeclaration);
        return(@namespace);
    }