Skip to content

Commit

Permalink
- code cleanup and additional unit tests for parameters mapping
Browse files Browse the repository at this point in the history
  • Loading branch information
baywet committed Jul 7, 2022
1 parent 4cc7b09 commit 8369af3
Show file tree
Hide file tree
Showing 2 changed files with 112 additions and 29 deletions.
61 changes: 33 additions & 28 deletions src/Kiota.Builder/KiotaBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -576,7 +576,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 @@ -1175,36 +1175,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 = GetPrimitiveType(parameter.Schema),
};
prop.Type.CollectionKind = parameter.Schema.IsArray() ? CodeTypeBase.CodeTypeCollectionKind.Array : default;
if(string.IsNullOrEmpty(prop.Type.Name))
prop.Type.Name = parameter.Schema?.Items?.Type ?? parameter.Schema?.Type ?? "string"; // since its a query parameter default to string if there is no schema

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
80 changes: 79 additions & 1 deletion tests/Kiota.Builder.Tests/KiotaBuilderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1714,8 +1714,86 @@ public void MapsQueryParameterTypes(string type, string format, string expected)
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 8369af3

Please sign in to comment.