Exemplo n.º 1
0
 public ParameterModel(string name, bool required, ParameterLocation?location, TypeReference type)
 {
     Name     = name;
     Required = required;
     Location = location;
     Type     = type;
 }
        private static void ProcessIn(OpenApiParameter o, ParseNode n)
        {
            var value = n.GetScalarValue();

            switch (value)
            {
            case "body":
                n.Context.SetTempStorage(TempStorageKeys.BodyParameter, o);
                break;

            case "formData":
                var formParameters = n.Context.GetFromTempStorage <List <OpenApiParameter> >("formParameters");
                if (formParameters == null)
                {
                    formParameters = new List <OpenApiParameter>();
                    n.Context.SetTempStorage("formParameters", formParameters);
                }

                formParameters.Add(o);
                break;

            default:
                _in  = value.GetEnumFromDisplayName <ParameterLocation>();
                o.In = _in;
                break;
            }
        }
        public static OpenApiParameter LoadParameter(ParseNode node, bool evenBody)
        {
            // Reset the local variables every time this method is called.
            _in = null;

            var mapNode = node.CheckMapNode("parameter");

            var pointer = mapNode.GetReferencePointer();

            if (pointer != null)
            {
                return(mapNode.GetReferencedObject <OpenApiParameter>(ReferenceType.Parameter, pointer));
            }

            var parameter = new OpenApiParameter();

            ParseMap(mapNode, parameter, _parameterFixedFields, _parameterPatternFields);

            var schema = node.Context.GetFromTempStorage <OpenApiSchema>("schema");

            if (schema != null)
            {
                parameter.Schema = schema;
                node.Context.SetTempStorage("schema", null);
            }

            if (_in == null && !evenBody)
            {
                return(null); // Don't include Form or Body parameters in OpenApiOperation.Parameters list
            }

            return(parameter);
        }
Exemplo n.º 4
0
        private static void ProcessIn(OpenApiParameter o, ParseNode n)
        {
            var value = n.GetScalarValue();

            switch (value)
            {
            // TODO: There could be multiple body/form parameters, so setting it to a global storage
            // will overwrite the old parameter. Need to handle this on a per-parameter basis.
            case "body":
                n.Context.SetTempStorage("bodyParameter", o);
                break;

            case "form":
                var formParameters = n.Context.GetFromTempStorage <List <OpenApiParameter> >("formParameters");
                if (formParameters == null)
                {
                    formParameters = new List <OpenApiParameter>();
                    n.Context.SetTempStorage("formParameters", formParameters);
                }
                formParameters.Add(o);
                break;

            default:
                _in  = value.GetEnumFromDisplayName <ParameterLocation>();
                o.In = _in;
                break;
            }
        }
Exemplo n.º 5
0
        public void i_can_compare_parameter_location_field(
            [Values(null, ParameterLocation.Cookie, ParameterLocation.Header, ParameterLocation.Path,
                    ParameterLocation.Query)]
            ParameterLocation?previous
            , [Values(null, ParameterLocation.Cookie, ParameterLocation.Header, ParameterLocation.Path,
                      ParameterLocation.Query)]
            ParameterLocation?actual)
        {
            const string parameterName = "parameter01";
            var          context       = ComparisonContext.FromPath("/path") with {
                Request = parameterName
            };
            var previousParameter = new OpenApiParameter()
            {
                In = previous
            };
            var actualParameter = new OpenApiParameter()
            {
                In = actual
            };
            var diffs = previousParameter.CompareTo(actualParameter, context).ToArray();

            Assert.AreEqual(previous == actual ? 0 : 1, diffs.Length, "unexpected differences count");
            foreach (DiffResult diff in diffs)
            {
                Assert.AreEqual(context, diff.Context, "unexpected context");
                TestContext.Progress.WriteLine($"[{diff.Context}] {diff.Kind}: '{diff.Message}'");
            }
        }
Exemplo n.º 6
0
        public static string CreateValueString(string name, string?format, ParameterLocation?parameterLocation, bool useForBadRequest, int itemNumber = 0, string?customValue = null)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (!string.IsNullOrEmpty(format))
            {
                if (format.Equals(OpenApiFormatTypeConstants.Email, StringComparison.OrdinalIgnoreCase))
                {
                    return(CreateValueEmail(useForBadRequest, itemNumber));
                }

                if (format.Equals(OpenApiFormatTypeConstants.Uri, StringComparison.OrdinalIgnoreCase))
                {
                    return(CreateValueUri(useForBadRequest));
                }
            }

            if (useForBadRequest && parameterLocation == ParameterLocation.Query)
            {
                return(string.Empty);
            }

            if (name.Equals("Id", StringComparison.OrdinalIgnoreCase) || name.EndsWith("Id", StringComparison.Ordinal))
            {
                return(CreateValueStringId(useForBadRequest, itemNumber, customValue));
            }

            return(CreateValueStringDefault(useForBadRequest, itemNumber, customValue));
        }
        public static PropertyDeclarationSyntax CreateAuto(
            ParameterLocation?parameterLocation,
            bool isNullable,
            bool isRequired,
            string dataType,
            string propertyName,
            bool useNullableReferenceTypes,
            IOpenApiAny?initializer)
        {
            if (useNullableReferenceTypes && (isNullable || parameterLocation == ParameterLocation.Query) && !isRequired)
            {
                dataType += "?";
            }

            var propertyDeclaration = CreateAuto(dataType, propertyName);

            if (initializer != null)
            {
                propertyDeclaration = initializer switch
                {
                    OpenApiInteger apiInteger => propertyDeclaration.WithInitializer(
                        SyntaxFactory.EqualsValueClause(SyntaxFactory.LiteralExpression(
                                                            SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(apiInteger !.Value))))
                    .WithSemicolonToken(SyntaxTokenFactory.Semicolon()),
                    OpenApiString apiString => propertyDeclaration.WithInitializer(
                        SyntaxFactory.EqualsValueClause(SyntaxFactory.LiteralExpression(
                                                            SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(apiString !.Value))))
                    .WithSemicolonToken(SyntaxTokenFactory.Semicolon()),
                    _ => throw new NotImplementedException("Property initializer: " + initializer.GetType())
                };
            }

            return(propertyDeclaration);
        }
Exemplo n.º 8
0
 public ChangedParameterBO(string name, ParameterLocation? @in, OpenApiParameter oldParameter,
                           OpenApiParameter newParameter, DiffContextBO context)
 {
     _context     = context;
     Name         = name;
     In           = @in;
     OldParameter = oldParameter;
     NewParameter = newParameter;
 }
Exemplo n.º 9
0
        static ParameterBinder ParameterLocationToParameterBinder(ParameterLocation?lo)
        {
            if (!lo.HasValue)
            {
                throw new System.IO.InvalidDataException("ParameterLocation is REQUIRED");
            }

            return(lo switch
            {
                ParameterLocation.Query => ParameterBinder.FromQuery,
                ParameterLocation.Path => ParameterBinder.FromUri,
                _ => ParameterBinder.None,                //so to be skiped/ignored
            });
Exemplo n.º 10
0
    public static PropertyDeclarationSyntax CreateAuto(
        ParameterLocation?parameterLocation,
        bool isNullable,
        bool isRequired,
        string dataType,
        string propertyName,
        bool useNullableReferenceTypes,
        IOpenApiAny?initializer)
    {
        switch (useNullableReferenceTypes)
        {
        case true when !isRequired && (isNullable || parameterLocation == ParameterLocation.Query):
        case true when isRequired && isNullable:
            dataType += "?";
            break;
        }

        var propertyDeclaration = CreateAuto(dataType, propertyName);

        if (initializer is null)
        {
            return(propertyDeclaration);
        }

        switch (initializer)
        {
        case OpenApiInteger apiInteger:
            propertyDeclaration = propertyDeclaration.WithInitializer(
                SyntaxFactory.EqualsValueClause(
                    SyntaxFactory.LiteralExpression(
                        SyntaxKind.NumericLiteralExpression,
                        SyntaxFactory.Literal(apiInteger !.Value))))
                                  .WithSemicolonToken(SyntaxTokenFactory.Semicolon());
            break;

        case OpenApiString apiString:
            var expressionSyntax = string.IsNullOrEmpty(apiString !.Value)
                    ? (ExpressionSyntax)SyntaxFactory.MemberAccessExpression(
                SyntaxKind.SimpleMemberAccessExpression,
                SyntaxFactory.PredefinedType(SyntaxTokenFactory.StringKeyword()),
                SyntaxFactory.IdentifierName("Empty"))
                    : SyntaxFactory.LiteralExpression(
                SyntaxKind.StringLiteralExpression,
                SyntaxFactory.Literal(apiString !.Value));

            propertyDeclaration = propertyDeclaration.WithInitializer(
                SyntaxFactory.EqualsValueClause(expressionSyntax))
                                  .WithSemicolonToken(SyntaxTokenFactory.Semicolon());

            break;

        case OpenApiBoolean apiBoolean when apiBoolean.Value:
            propertyDeclaration = propertyDeclaration.WithInitializer(
                SyntaxFactory.EqualsValueClause(
                    SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression)))
                                  .WithSemicolonToken(SyntaxTokenFactory.Semicolon());
            break;

        case OpenApiBoolean apiBoolean when !apiBoolean.Value:
            propertyDeclaration = propertyDeclaration.WithInitializer(
                SyntaxFactory.EqualsValueClause(
                    SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression)))
                                  .WithSemicolonToken(SyntaxTokenFactory.Semicolon());
            break;

        default:
            throw new NotImplementedException("Property initializer: " + initializer.GetType());
        }

        return(propertyDeclaration);
    }
Exemplo n.º 11
0
        private RestEaseParameter BuildValidParameter(string identifier, OpenApiSchema schema, bool required, string description, ParameterLocation? parameterLocation, params string[] extraAttributes)
        {
            var attributes = new List<string>();
            string validIdentifier = CSharpUtils.CreateValidIdentifier(identifier, CasingType.Camel);

            string restEaseParameterAnnotation = parameterLocation != null ? parameterLocation.ToString() : string.Empty;
            string isNullPostfix = !required && Settings.MakeNonRequiredParametersOptional ? " = null" : string.Empty;

            if (parameterLocation == ParameterLocation.Header)
            {
                attributes.Add($"\"{identifier}\"");
            }

            object identifierWithType;
            if (identifier != validIdentifier)
            {
                switch (parameterLocation)
                {
                    case ParameterLocation.Path:
                    case ParameterLocation.Query:
                        attributes.Add($"Name = \"{identifier}\"");
                        break;
                }

                attributes.AddRange(extraAttributes);

                identifierWithType = MapSchema(schema, validIdentifier, !required, false, null);

                return new RestEaseParameter
                {
                    Required = required,
                    Identifier = validIdentifier,
                    SchemaType = schema.GetSchemaType(),
                    SchemaFormat = schema.GetSchemaFormat(),
                    IdentifierWithType = $"{identifierWithType}",
                    IdentifierWithRestEase = $"[{restEaseParameterAnnotation}({string.Join(", ", attributes)})] {identifierWithType}{isNullPostfix}",
                    Summary = description
                };
            }

            string extraAttributesBetweenParentheses = extraAttributes.Length == 0 ? string.Empty : $"({string.Join(", ", extraAttributes)})";
            identifierWithType = MapSchema(schema, identifier, !required, false, null);

            return new RestEaseParameter
            {
                Required = required,
                Identifier = identifier,
                SchemaType = schema.GetSchemaType(),
                SchemaFormat = schema.GetSchemaFormat(),
                IdentifierWithType = $"{identifierWithType}",
                IdentifierWithRestEase = $"[{restEaseParameterAnnotation}{extraAttributesBetweenParentheses}] {identifierWithType}{isNullPostfix}",
                Summary = description
            };
        }
 /// <summary>
 ///
 /// </summary>
 public OpenApiParameterRule(string fieldName, ParameterLocation?inParameterLocation, IValidatorContext context, OpenApiParameter element) : base(context, element)
 {
     this.RequestElementName  = fieldName;
     this.InParameterLocation = inParameterLocation;
     this._required           = element.Required;
 }