Skip to content

Commit

Permalink
Merge pull request #1723 from microsoft/bugfix/query-parameters-type
Browse files Browse the repository at this point in the history
- fixes a bug where query parameters types would ignore the format
  • Loading branch information
baywet authored Jul 8, 2022
2 parents 0844148 + 8369af3 commit d3ff8f2
Show file tree
Hide file tree
Showing 3 changed files with 177 additions and 31 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- Fixed a bug where query parameter types would not consider the format. [#1721](https://github.com/microsoft/kiota/issues/1721)
- Fixed a bug where discriminator mappings across namespaces could create circular dependencies in Go. [#1712](https://github.com/microsoft/kiota/issues/1712)
- Fixed a bug where Go binary downloads would try to parse a structured object.
- Aligned mime types model generation behaviour for request bodies on response content. [#134](https://github.com/microsoft/kiota/issues/134)
Expand Down
63 changes: 33 additions & 30 deletions src/Kiota.Builder/KiotaBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -577,7 +577,7 @@ private static CodeType GetPrimitiveType(OpenApiSchema typeSchema, string childT
if(typeSchema?.AnyOf?.Any() ?? false)
typeNames.AddRange(typeSchema.AnyOf.Select(x => x.Type)); // double is sometimes an anyof string, number and enum
// first value that's not null, and not "object" for primitive collections, the items type matters
var typeName = typeNames.FirstOrDefault(x => !string.IsNullOrEmpty(x) && !typeNamesToSkip.Contains(x));
var typeName = typeNames.FirstOrDefault(static x => !string.IsNullOrEmpty(x) && !typeNamesToSkip.Contains(x));

var isExternal = false;
if (typeSchema?.Items?.Enum?.Any() ?? false)
Expand Down Expand Up @@ -1184,38 +1184,41 @@ private CodeClass CreateOperationParameterClass(OpenApiUrlTreeNode node, Operati
Description = (operation.Description ?? operation.Summary).CleanupDescription(),
}).First();
foreach (var parameter in parameters)
{
var prop = new CodeProperty
{
Name = parameter.Name.SanitizeParameterNameForCodeSymbols(),
Description = parameter.Description.CleanupDescription(),
Kind = CodePropertyKind.QueryParameter,
Type = new CodeType
{
IsExternal = true,
Name = parameter.Schema?.Items?.Type ?? parameter.Schema?.Type ?? "string", // since its a query parameter default to string if there is no schema
CollectionKind = parameter.Schema.IsArray() ? CodeType.CodeTypeCollectionKind.Array : default,
},
};

if(!parameter.Name.Equals(prop.Name))
{
prop.SerializationName = parameter.Name.SanitizeParameterNameForUrlTemplate();
}

if (!parameterClass.ContainsMember(parameter.Name))
{
parameterClass.AddProperty(prop);
}
else
{
logger.LogWarning("Ignoring duplicate parameter {name}", parameter.Name);
}
}

AddPropertyForParameter(parameter, parameterClass);

return parameterClass;
} else return null;
}
private void AddPropertyForParameter(OpenApiParameter parameter, CodeClass parameterClass) {
var prop = new CodeProperty
{
Name = parameter.Name.SanitizeParameterNameForCodeSymbols(),
Description = parameter.Description.CleanupDescription(),
Kind = CodePropertyKind.QueryParameter,
Type = GetPrimitiveType(parameter.Schema),
};
prop.Type.CollectionKind = parameter.Schema.IsArray() ? CodeTypeBase.CodeTypeCollectionKind.Array : default;
if(string.IsNullOrEmpty(prop.Type.Name) && prop.Type is CodeType parameterType) {
// since its a query parameter default to string if there is no schema
// it also be an object type, but we'd need to create the model in that case and there's no standard on how to serialize those as query parameters
parameterType.Name = "string";
parameterType.IsExternal = true;
}

if(!parameter.Name.Equals(prop.Name))
{
prop.SerializationName = parameter.Name.SanitizeParameterNameForUrlTemplate();
}

if (!parameterClass.ContainsMember(parameter.Name))
{
parameterClass.AddProperty(prop);
}
else
{
logger.LogWarning("Ignoring duplicate parameter {name}", parameter.Name);
}
}
private static CodeType GetQueryParameterType(OpenApiSchema schema) =>
new()
{
Expand Down
144 changes: 143 additions & 1 deletion tests/Kiota.Builder.Tests/KiotaBuilderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1650,8 +1650,150 @@ public void MapsPrimitiveFormats(string type, string format, string expected){
Assert.Equal(expected, method.ReturnType.Name);
Assert.True(method.ReturnType.AllTypes.First().IsExternal);
}
[InlineData("string", "", "string")]// https://spec.openapis.org/registry/format/
[InlineData("string", "commonmark", "string")]
[InlineData("string", "html", "string")]
[InlineData("string", "date-time", "DateTimeOffset")]
[InlineData("string", "duration", "TimeSpan")]
[InlineData("string", "date", "DateOnly")]
[InlineData("string", "time", "TimeOnly")]
[InlineData("string", "base64url", "binary")]
// floating points can only be declared as numbers
[InlineData("number", "double", "double")]
[InlineData("number", "float", "float")]
[InlineData("number", "decimal", "decimal")]
// integers can only be declared as numbers or integers
[InlineData("number", "int32", "integer")]
[InlineData("integer", "int32", "integer")]
[InlineData("number", "int64", "int64")]
[InlineData("integer", "int64", "int64")]
[InlineData("number", "int8", "sbyte")]
[InlineData("integer", "int8", "sbyte")]
[InlineData("number", "uint8", "byte")]
[InlineData("integer", "uint8", "byte")]
[InlineData("number", "", "int64")]
[InlineData("integer", "", "integer")]
[InlineData("boolean", "", "boolean")]
[InlineData("", "byte", "binary")]
[InlineData("", "binary", "binary")]
[InlineData("file", null, "binary")]
[Theory]
public void MapsQueryParameterTypes(string type, string format, string expected){
var document = new OpenApiDocument() {
Paths = new OpenApiPaths() {
["primitive"] = new OpenApiPathItem() {
Operations = {
[OperationType.Get] = new OpenApiOperation() {
Parameters = new List<OpenApiParameter> {
new OpenApiParameter {
Name = "query",
In = ParameterLocation.Query,
Schema = new OpenApiSchema {
Type = type,
Format = format
}
}
},
Responses = new OpenApiResponses
{
["204"] = new OpenApiResponse {}
}
}
}
}
},
};
var mockLogger = new Mock<ILogger<KiotaBuilder>>();
var builder = new KiotaBuilder(mockLogger.Object, new GenerationConfiguration() { ClientClassName = "Graph", ApiRootUrl = "https://localhost" });
var node = builder.CreateUriSpace(document);
var codeModel = builder.CreateSourceModel(node);
var queryParameters = codeModel.FindChildByName<CodeClass>("primitiveRequestBuilderGetQueryParameters", true);
Assert.NotNull(queryParameters);
var property = queryParameters.Properties.First(static x => x.Name.Equals("query", StringComparison.OrdinalIgnoreCase));
Assert.NotNull(property);
Assert.Equal(expected, property.Type.Name);
Assert.True(property.Type.AllTypes.First().IsExternal);
}
[InlineData(true)]
[InlineData(false)]
[Theory]
public void MapsQueryParameterCollectionKinds(bool isArray){
var baseSchema = new OpenApiSchema {
Type = "number",
Format = "int64"
};
var arraySchema = new OpenApiSchema {
Type = "array",
Items = baseSchema
};
var document = new OpenApiDocument() {
Paths = new OpenApiPaths() {
["primitive"] = new OpenApiPathItem() {
Operations = {
[OperationType.Get] = new OpenApiOperation() {
Parameters = new List<OpenApiParameter> {
new OpenApiParameter {
Name = "query",
In = ParameterLocation.Query,
Schema = isArray ? arraySchema : baseSchema
}
},
Responses = new OpenApiResponses
{
["204"] = new OpenApiResponse {}
}
}
}
}
},
};
var mockLogger = new Mock<ILogger<KiotaBuilder>>();
var builder = new KiotaBuilder(mockLogger.Object, new GenerationConfiguration() { ClientClassName = "Graph", ApiRootUrl = "https://localhost" });
var node = builder.CreateUriSpace(document);
var codeModel = builder.CreateSourceModel(node);
var queryParameters = codeModel.FindChildByName<CodeClass>("primitiveRequestBuilderGetQueryParameters", true);
Assert.NotNull(queryParameters);
var property = queryParameters.Properties.First(static x => x.Name.Equals("query", StringComparison.OrdinalIgnoreCase));
Assert.NotNull(property);
Assert.Equal("int64", property.Type.Name);
Assert.Equal(isArray ? CodeTypeBase.CodeTypeCollectionKind.Array : CodeTypeBase.CodeTypeCollectionKind.None, property.Type.CollectionKind);
Assert.True(property.Type.AllTypes.First().IsExternal);
}
[Fact]
public void DefaultsQueryParametersWithNoSchemaToString(){
var document = new OpenApiDocument() {
Paths = new OpenApiPaths() {
["primitive"] = new OpenApiPathItem() {
Operations = {
[OperationType.Get] = new OpenApiOperation() {
Parameters = new List<OpenApiParameter> {
new OpenApiParameter {
Name = "query",
In = ParameterLocation.Query
}
},
Responses = new OpenApiResponses
{
["204"] = new OpenApiResponse {}
}
}
}
}
},
};
var mockLogger = new Mock<ILogger<KiotaBuilder>>();
var builder = new KiotaBuilder(mockLogger.Object, new GenerationConfiguration() { ClientClassName = "Graph", ApiRootUrl = "https://localhost" });
var node = builder.CreateUriSpace(document);
var codeModel = builder.CreateSourceModel(node);
var queryParameters = codeModel.FindChildByName<CodeClass>("primitiveRequestBuilderGetQueryParameters", true);
Assert.NotNull(queryParameters);
var property = queryParameters.Properties.First(static x => x.Name.Equals("query", StringComparison.OrdinalIgnoreCase));
Assert.NotNull(property);
Assert.Equal("string", property.Type.Name);
Assert.True(property.Type.AllTypes.First().IsExternal);
}
[Fact]
public void DoesntGenerateNamesapacesWhenNotRequired(){
public void DoesntGenerateNamespacesWhenNotRequired(){
var myObjectSchema = new OpenApiSchema {
Type = "object",
Properties = new Dictionary<string, OpenApiSchema> {
Expand Down

0 comments on commit d3ff8f2

Please sign in to comment.