Skip to content

Commit

Permalink
Merge pull request #3341 from microsoft/feature/ts-conventions-refact…
Browse files Browse the repository at this point in the history
…oring

- refactoring: removes inline type writing in typescript
  • Loading branch information
baywet authored Sep 20, 2023
2 parents 6b0d621 + 4953c1e commit ba2f65d
Show file tree
Hide file tree
Showing 6 changed files with 12 additions and 46 deletions.
21 changes: 8 additions & 13 deletions src/Kiota.Builder/Writers/TypeScript/CodeMethodWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ public CodeMethodWriter(TypeScriptConventionService conventionService, bool uses
{
_usesBackingStore = usesBackingStore;
}
private TypeScriptConventionService? localConventions;
private readonly bool _usesBackingStore;

public override void WriteCodeElement(CodeMethod codeElement, LanguageWriter writer)
Expand All @@ -23,8 +22,7 @@ public override void WriteCodeElement(CodeMethod codeElement, LanguageWriter wri
if (codeElement.Parent is CodeFunction) return;
if (codeElement.Parent is not CodeClass parentClass) throw new InvalidOperationException("the parent of a method should be a class");

localConventions = new TypeScriptConventionService(writer); //because we allow inline type definitions for methods parameters
var returnType = localConventions.GetTypeString(codeElement.ReturnType, codeElement);
var returnType = conventions.GetTypeString(codeElement.ReturnType, codeElement);
var isVoid = "void".EqualsIgnoreCase(returnType);
WriteMethodDocumentation(codeElement, writer, isVoid);
WriteMethodPrototype(codeElement, writer, returnType, isVoid);
Expand Down Expand Up @@ -126,10 +124,9 @@ internal static void WriteDefensiveStatements(CodeMethod codeElement, LanguageWr
private void WriteIndexerBody(CodeMethod codeElement, CodeClass parentClass, string returnType, LanguageWriter writer)
{
if (parentClass.GetPropertyOfKind(CodePropertyKind.PathParameters) is CodeProperty pathParametersProperty &&
localConventions != null &&
codeElement.OriginalIndexer != null)
{
localConventions.AddParametersAssignment(writer, pathParametersProperty.Type, $"this.{pathParametersProperty.Name}",
conventions.AddParametersAssignment(writer, pathParametersProperty.Type, $"this.{pathParametersProperty.Name}",
parameters: (codeElement.OriginalIndexer.IndexParameter.Type, codeElement.OriginalIndexer.IndexParameter.SerializationName, codeElement.OriginalIndexer.IndexParameter.Name.ToFirstCharacterLowerCase()));
}
conventions.AddRequestBuilderBody(parentClass, returnType, writer, conventions.TempDictionaryVarName);
Expand Down Expand Up @@ -242,7 +239,7 @@ private void WriteConstructorBody(CodeClass parentClass, CodeMethod currentMetho
currentMethod.Parameters.FirstOrDefault(static x => x.IsOfKind(CodeParameterKind.PathParameters)) is CodeParameter pathParametersParam &&
parentClass.Properties.FirstOrDefaultOfKind(CodePropertyKind.PathParameters) is CodeProperty pathParametersProperty)
{
localConventions?.AddParametersAssignment(writer,
conventions.AddParametersAssignment(writer,
pathParametersParam.Type.AllTypes.OfType<CodeType>().First(),
pathParametersParam.Name.ToFirstCharacterLowerCase(),
$"this.{pathParametersProperty.Name.ToFirstCharacterLowerCase()}",
Expand Down Expand Up @@ -385,7 +382,7 @@ private void WriteRequestGeneratorBody(CodeMethod codeElement, RequestParams req

private void ComposeContentInRequestGeneratorBody(CodeParameter requestBody, CodeProperty requestAdapterProperty, string contentType, LanguageWriter writer)
{
if (requestBody.Type.Name.Equals(localConventions?.StreamTypeName, StringComparison.OrdinalIgnoreCase))
if (requestBody.Type.Name.Equals(conventions.StreamTypeName, StringComparison.OrdinalIgnoreCase))
{
writer.WriteLine($"{RequestInfoVarName}.setStreamContent({requestBody.Name});");
return;
Expand Down Expand Up @@ -423,8 +420,7 @@ private void WriteMethodDocumentation(CodeMethod code, LanguageWriter writer, bo
private static readonly BaseCodeParameterOrderComparer parameterOrderComparer = new();
private void WriteMethodPrototype(CodeMethod code, LanguageWriter writer, string returnType, bool isVoid)
{
if (localConventions != null)
WriteMethodPrototypeInternal(code, writer, returnType, isVoid, localConventions, false);
WriteMethodPrototypeInternal(code, writer, returnType, isVoid, conventions, false);
}
internal static void WriteMethodPrototypeInternal(CodeMethod code, LanguageWriter writer, string returnType, bool isVoid, TypeScriptConventionService pConventions, bool isFunction)
{
Expand Down Expand Up @@ -455,9 +451,8 @@ internal static void WriteMethodPrototypeInternal(CodeMethod code, LanguageWrite
}
private string GetFactoryMethodName(CodeTypeBase targetClassType, CodeMethod currentElement, LanguageWriter writer)
{
if (localConventions == null) throw new InvalidOperationException("localConventions is null");
var returnType = localConventions.GetTypeString(targetClassType, currentElement, false, writer);
var targetClassName = localConventions.TranslateType(targetClassType);
var returnType = conventions.GetTypeString(targetClassType, currentElement, false, writer);
var targetClassName = conventions.TranslateType(targetClassType);
var resultName = $"create{targetClassName.ToFirstCharacterUpperCase()}FromDiscriminatorValue";
if (targetClassName.Equals(returnType, StringComparison.OrdinalIgnoreCase))
return resultName;
Expand All @@ -466,7 +461,7 @@ currentType.TypeDefinition is CodeClass definitionClass &&
definitionClass.GetImmediateParentOfType<CodeNamespace>() is CodeNamespace parentNamespace &&
parentNamespace.FindChildByName<CodeFunction>(resultName) is CodeFunction factoryMethod)
{
var methodName = localConventions.GetTypeString(new CodeType
var methodName = conventions.GetTypeString(new CodeType
{
Name = resultName,
TypeDefinition = factoryMethod
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,6 @@
namespace Kiota.Builder.Writers.TypeScript;
public class TypeScriptConventionService : CommonLanguageConventionService
{
public TypeScriptConventionService(LanguageWriter languageWriter)
{
writer = languageWriter;
}
internal void WriteAutoGeneratedStart(LanguageWriter writer)
{
writer.WriteLine("// tslint:disable");
Expand All @@ -26,7 +22,6 @@ internal void WriteAutoGeneratedEnd(LanguageWriter writer)
writer.WriteLine("// tslint:enable");
writer.WriteLine("// eslint-enable");
}
private readonly LanguageWriter writer;
public override string StreamTypeName => "ArrayBuffer";
public override string VoidTypeName => "void";
public override string DocCommentPrefix => " * ";
Expand Down Expand Up @@ -86,8 +81,6 @@ public override string GetTypeString(CodeTypeBase code, CodeElement targetElemen
if (code is CodeType currentType)
{
var typeName = GetTypeAlias(currentType, targetElement) is string alias && !string.IsNullOrEmpty(alias) ? alias : TranslateType(currentType);
if (code.ActionOf)
return WriteInlineDeclaration(currentType, targetElement);
return $"{typeName}{collectionSuffix}";
}

Expand All @@ -104,27 +97,6 @@ private static string GetTypeAlias(CodeType targetType, CodeElement targetElemen
return aliasedUsing.Alias;
return string.Empty;
}
private string WriteInlineDeclaration(CodeType currentType, CodeElement targetElement)
{
writer.IncreaseIndent(4);
var childElements = (currentType?.TypeDefinition as CodeClass)
?.Properties
?.OrderBy(x => x.Name)
?.Select(x => $"{x.Name}?: {GetTypeString(x.Type, targetElement)}");
var innerDeclaration = childElements?.Any() ?? false ?
LanguageWriter.NewLine +
writer.GetIndent() +
childElements
.Aggregate((x, y) => $"{x};{LanguageWriter.NewLine}{writer.GetIndent()}{y}")
.Replace(';', ',') +
LanguageWriter.NewLine +
writer.GetIndent()
: string.Empty;
writer.DecreaseIndent();
if (string.IsNullOrEmpty(innerDeclaration))
return "object";
return $"{{{innerDeclaration}}}";
}

public override string TranslateType(CodeType type)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Kiota.Builder/Writers/TypeScript/TypeScriptWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ public class TypeScriptWriter : LanguageWriter
public TypeScriptWriter(string rootPath, string clientNamespaceName, bool usesBackingStore = false)
{
PathSegmenter = new TypeScriptPathSegmenter(rootPath, clientNamespaceName);
var conventionService = new TypeScriptConventionService(this);
var conventionService = new TypeScriptConventionService();
AddOrReplaceCodeElementWriter(new CodeClassDeclarationWriter(conventionService, clientNamespaceName));
AddOrReplaceCodeElementWriter(new CodeBlockEndWriter(conventionService));
AddOrReplaceCodeElementWriter(new CodeEnumWriter(conventionService));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class CodeClassDeclarationWriterTests : IDisposable
public CodeClassDeclarationWriterTests()
{
writer = LanguageWriter.GetLanguageWriter(GenerationLanguage.TypeScript, DefaultPath, DefaultName);
codeElementWriter = new CodeClassDeclarationWriter(new TypeScriptConventionService(writer), "graphtests");
codeElementWriter = new CodeClassDeclarationWriter(new TypeScriptConventionService(), "graphtests");
tw = new StringWriter();
writer.SetTextWriter(tw);
var root = CodeNamespace.InitRootNamespace();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class CodeClassEndWriterTests : IDisposable
public CodeClassEndWriterTests()
{
writer = LanguageWriter.GetLanguageWriter(GenerationLanguage.TypeScript, DefaultPath, DefaultName);
codeElementWriter = new CodeBlockEndWriter(new(writer));
codeElementWriter = new CodeBlockEndWriter(new());
tw = new StringWriter();
writer.SetTextWriter(tw);
var root = CodeNamespace.InitRootNamespace();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,6 @@ private void AddRequestBodyParameters(bool useComplexTypeForBody = false)
{
Name = "RequestConfig",
TypeDefinition = requestConfigClass,
ActionOf = true,
},
Optional = true,
});
Expand Down Expand Up @@ -392,7 +391,7 @@ public void WritesMethodDescriptionLink()
[Fact]
public void Defensive()
{
var codeMethodWriter = new CodeMethodWriter(new TypeScriptConventionService(writer), false);
var codeMethodWriter = new CodeMethodWriter(new TypeScriptConventionService(), false);
Assert.Throws<ArgumentNullException>(() => codeMethodWriter.WriteCodeElement(null, writer));
Assert.Throws<ArgumentNullException>(() => codeMethodWriter.WriteCodeElement(method, null));
var originalParent = method.Parent;
Expand Down

0 comments on commit ba2f65d

Please sign in to comment.