Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix TS Code file #3376

Merged
merged 6 commits into from
Oct 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Adds codes files in typescript to reduce number of generated files. [#2116](https://github.com/microsoft/kiota/issues/2116)
- Fix null reference exception when a parameter is defined without a schema. (CLI).
- Log a message to stderr if a request is skipped due to missing data. (CLI) [#2210](https://github.com/microsoft/kiota/issues/2210)
- Fixes code file generation in typescript [#3419](https://github.com/microsoft/kiota/issues/3419)

## [1.6.1] - 2023-09-11

Expand Down
15 changes: 11 additions & 4 deletions src/Kiota.Builder/Refiners/TypeScriptRefiner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -174,15 +174,15 @@ private void MergeElementsToFile(CodeElement currentElement)

private static void GenerateModelCodeFile(CodeInterface codeInterface, CodeNamespace codeNamespace)
{
List<CodeElement> functions = new List<CodeElement> { codeInterface };
List<CodeElement> functions = new List<CodeElement>();

foreach (var element in codeNamespace.GetChildElements(true))
{
if (element is CodeFunction codeFunction)
{
if (codeFunction.OriginalLocalMethod.IsOfKind(CodeMethodKind.Deserializer, CodeMethodKind.Serializer) &&
codeFunction.OriginalLocalMethod.Parameters
.Any(x => x?.Type?.Name?.Equals(codeInterface.Name, StringComparison.OrdinalIgnoreCase) ?? false))
.Any(x => x.Type.Name?.Equals(codeInterface.Name, StringComparison.OrdinalIgnoreCase) ?? false))
{
functions.Add(codeFunction);
}
Expand All @@ -195,6 +195,10 @@ private static void GenerateModelCodeFile(CodeInterface codeInterface, CodeNames
}
}

if (!functions.Any())
return;

functions.Insert(0, codeInterface);
codeNamespace.TryAddCodeFile(codeInterface.Name, functions.ToArray());
}

Expand All @@ -204,18 +208,21 @@ private static void GenerateRequestBuilderCodeFile(CodeClass codeClass, CodeName
.Where(static x => x.IsOfKind(CodeMethodKind.RequestGenerator))
.SelectMany(static x => x.Parameters)
.Where(static x => x.IsOfKind(CodeParameterKind.RequestConfiguration))
.Select(static x => x?.Type?.Name)
.Select(static x => x.Type?.Name)
.Where(static x => !string.IsNullOrEmpty(x))
.OfType<string>()
.ToList();

if (!elementNames.Any())
return;

List<CodeInterface> configClasses = codeNamespace.FindChildrenByName<CodeInterface>(elementNames, false)
.Where(static x => x != null)
.OfType<CodeInterface>()
.ToList();

List<string> queryParamClassNames = configClasses.Where(x => x != null)
.Select(static w => w.GetPropertyOfKind(CodePropertyKind.QueryParameters)?.Type?.Name)
.Select(static w => w.GetPropertyOfKind(CodePropertyKind.QueryParameters)?.Type.Name)
.Where(static x => !string.IsNullOrEmpty(x))
.OfType<string>()
.ToList();
Expand Down
17 changes: 17 additions & 0 deletions src/Kiota.Builder/Writers/TypeScript/CodeFileBlockEndWriter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;
using Kiota.Builder.CodeDOM;
namespace Kiota.Builder.Writers.TypeScript;

public class CodeFileBlockEndWriter : BaseElementWriter<CodeFileBlockEnd, TypeScriptConventionService>
{
public CodeFileBlockEndWriter(TypeScriptConventionService conventionService) : base(conventionService)
{
}

public override void WriteCodeElement(CodeFileBlockEnd codeElement, LanguageWriter writer)
{
ArgumentNullException.ThrowIfNull(codeElement);
ArgumentNullException.ThrowIfNull(writer);
conventions.WriteAutoGeneratedEnd(writer);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,18 @@ public override void WriteCodeElement(CodeFileDeclaration codeElement, LanguageW
};
}
);
_codeUsingWriter.WriteCodeElement(usings, ns, writer);
conventions.WriteAutoGeneratedStart(writer);

// remove duplicate using, keep a single using for each internal type in the same namespace
var enumeratedUsing = usings.ToArray();
var filteredUsing = enumeratedUsing.Where(static x => x.IsExternal)
.Union(enumeratedUsing
.Where(static x => x is { IsExternal: false, Declaration.TypeDefinition: not null })
.GroupBy(static x =>
$"{x.Declaration!.TypeDefinition!.GetImmediateParentOfType<CodeNamespace>().Name}.{x.Declaration?.Name.ToLowerInvariant()}")
.Select(static x => x.OrderBy(static x => x.Parent?.Name).First()));

_codeUsingWriter.WriteCodeElement(filteredUsing, ns, writer);
}
}

Expand Down
16 changes: 9 additions & 7 deletions src/Kiota.Builder/Writers/TypeScript/CodeFunctionWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ public override void WriteCodeElement(CodeFunction codeElement, LanguageWriter w

if (codeElement.Parent is not CodeNamespace && codeElement.Parent is not CodeFile) throw new InvalidOperationException("the parent of a function should be a namespace or file");

conventions.WriteAutoGeneratedStart(writer);
if (codeElement.Parent is CodeNamespace)
{
conventions.WriteAutoGeneratedStart(writer);
_codeUsingWriter.WriteCodeElement(codeElement.StartBlock.Usings, codeElement.GetImmediateParentOfType<CodeNamespace>(), writer);
}

Expand Down Expand Up @@ -246,13 +246,15 @@ private string GetFactoryMethodName(CodeTypeBase targetClassType, CodeMethod cur
{
var resultName = $"create{targetClassName.ToFirstCharacterUpperCase()}FromDiscriminatorValue";
if (conventions.GetTypeString(targetClassType, currentElement, false) is string returnType && targetClassName.EqualsIgnoreCase(returnType)) return resultName;
if (targetClassType is CodeType currentType &&
currentType.TypeDefinition is CodeInterface definitionClass &&
definitionClass.GetImmediateParentOfType<CodeNamespace>() is CodeNamespace parentNamespace &&
parentNamespace.FindChildByName<CodeFunction>(resultName) is CodeFunction factoryMethod)
if (targetClassType is CodeType currentType && currentType.TypeDefinition is CodeInterface definitionClass)
{
var methodName = conventions.GetTypeString(new CodeType { Name = resultName, TypeDefinition = factoryMethod }, currentElement, false);
return methodName.ToFirstCharacterUpperCase();// static function is aliased
var factoryMethod = definitionClass.GetImmediateParentOfType<CodeFile>()?.FindChildByName<CodeFunction>(resultName) ??
definitionClass.GetImmediateParentOfType<CodeNamespace>()?.FindChildByName<CodeFunction>(resultName);
if (factoryMethod != null)
{
var methodName = conventions.GetTypeString(new CodeType { Name = resultName, TypeDefinition = factoryMethod }, currentElement, false);
return methodName.ToFirstCharacterUpperCase();// static function is aliased
}
}
}
throw new InvalidOperationException($"Unable to find factory method for {targetClassType}");
Expand Down
1 change: 1 addition & 0 deletions src/Kiota.Builder/Writers/TypeScript/TypeScriptWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public TypeScriptWriter(string rootPath, string clientNamespaceName, bool usesBa
AddOrReplaceCodeElementWriter(new CodeTypeWriter(conventionService));
AddOrReplaceCodeElementWriter(new CodeNameSpaceWriter(conventionService));
AddOrReplaceCodeElementWriter(new CodeInterfaceDeclarationWriter(conventionService, clientNamespaceName));
AddOrReplaceCodeElementWriter(new CodeFileBlockEndWriter(conventionService));
AddOrReplaceCodeElementWriter(new CodeFileDeclarationWriter(conventionService, clientNamespaceName));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Kiota.Builder.CodeDOM;
using Kiota.Builder.Configuration;
using Kiota.Builder.Extensions;
using Kiota.Builder.Refiners;
using Kiota.Builder.Writers;
using Xunit;

namespace Kiota.Builder.Tests.Writers.TypeScript;

public class CodeFileWriterTests
{
private const string DefaultPath = "./";
private const string DefaultName = "name";
private readonly StringWriter tw;
private readonly LanguageWriter writer;
private readonly CodeNamespace root;
private const string MethodName = "methodName";
private const string ReturnTypeName = "Somecustomtype";

public CodeFileWriterTests()
{
writer = LanguageWriter.GetLanguageWriter(GenerationLanguage.TypeScript, DefaultPath, DefaultName);
tw = new StringWriter();
writer.SetTextWriter(tw);
root = CodeNamespace.InitRootNamespace();
}

[Fact]
public void Dispose()
{
tw?.Dispose();
GC.SuppressFinalize(this);
}

private void WriteCode(LanguageWriter writer, CodeElement element)
{
writer.Write(element);
if (element is not CodeNamespace)
foreach (var childElement in element.GetChildElements()
.Order(new CodeElementOrderComparer()))
{
WriteCode(writer, childElement);
}

}

[Fact]
public async Task WritesAutoGenerationStart()
{
var parentClass = TestHelper.CreateModelClass(root, "parentClass", true);
TestHelper.AddSerializationPropertiesToModelClass(parentClass);
await ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.TypeScript }, root);
var codeFile = root.FindChildByName<CodeFile>(parentClass.Name.ToFirstCharacterUpperCase());
WriteCode(writer, codeFile);

var result = tw.ToString();
Assert.Contains("// eslint-disable", result);
Assert.Contains("// tslint:disable", result);
Assert.Contains("export function deserializeIntoParentClass", result);
Assert.Contains("export interface ParentClass", result);
Assert.Contains("export function serializeParentClass", result);
Assert.Contains("// eslint-enable", result);
Assert.Contains("// tslint:enable", result);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ public async Task WritesAutoGenerationStart()
var serializeFunction = root.FindChildByName<CodeFunction>($"deserializeInto{parentClass.Name.ToFirstCharacterUpperCase()}");
writer.Write(serializeFunction);
var result = tw.ToString();
Assert.Contains("// eslint-disable", result);
Assert.Contains("// tslint:disable", result);
Assert.DoesNotContain("// eslint-disable", result);
Assert.DoesNotContain("// tslint:disable", result);
}
[Fact]
public async Task WritesAutoGenerationEnd()
Expand Down
Loading