Skip to content

Commit

Permalink
Merge pull request #4427 from andreaTP/issue-4426
Browse files Browse the repository at this point in the history
[TS] Fix codegen for endpoint returning enums
  • Loading branch information
andrueastman authored Apr 4, 2024
2 parents f6312c5 + f01c51a commit bf2f42c
Show file tree
Hide file tree
Showing 9 changed files with 86 additions and 7 deletions.
3 changes: 2 additions & 1 deletion .github/workflows/integration-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ jobs:
- python
description:
- "./tests/Kiota.Builder.IntegrationTests/InheritingErrors.yaml"
- "./tests/Kiota.Builder.IntegrationTests/EnumHandling.yaml"
- "./tests/Kiota.Builder.IntegrationTests/NoUnderscoresInModel.yaml"
- "./tests/Kiota.Builder.IntegrationTests/ToDoApi.yaml"
- "./tests/Kiota.Builder.IntegrationTests/GeneratesUritemplateHints.yaml"
Expand All @@ -59,7 +60,7 @@ jobs:
- "apisguru::docusign.net"
- "apisguru::github.com:api.github.com"
- "apisguru::apis.guru"

steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Added a warning message in the CLI when using preview languages. [#4316](https://github.com/microsoft/kiota/issues/4316)
- Added support for handling untyped Json content in C#,Golang, TypeScript and Java. [#2319](https://github.com/microsoft/kiota/issues/2319)
- Added TypeScript typecheck suppression to `.ts` files where unused imports cause build fail in projects which use `noUnusedLocals: true` compiler option. [#4397](https://github.com/microsoft/kiota/issues/4397)
- Fixed TypeScript generation bug when returning enums from endpoints. [#4426](https://github.com/microsoft/kiota/issues/4426)

### Changed

Expand Down
4 changes: 2 additions & 2 deletions it/typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "0.0.1",
"license": "MIT",
"scripts": {
"build": "node ./build/esbuild.js --dev",
"build": "tsc -noEmit && node ./build/esbuild.js --dev",
"build:meta": "node ./build/esbuild.js --dev --meta",
"build:meta:prod": "node ./build/esbuild.js --meta",
"build:prod": "node ./build/esbuild.js",
Expand Down Expand Up @@ -41,4 +41,4 @@
"express": "^4.19.2",
"node-fetch": "^2.7.0"
}
}
}
4 changes: 2 additions & 2 deletions it/typescript/src/app/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Logger } from './common/logger';
import { DeviceCodeCredential } from '@azure/identity';
import { FetchRequestAdapter } from '@microsoft/kiota-http-fetchlibrary';
import { AzureIdentityAuthenticationProvider } from '@microsoft/kiota-authentication-azure';
import { type ApiClient } from './client/apiClient';
import { createApiClient } from './client/apiClient';

export class App {
static run(): App {
Expand All @@ -19,7 +19,7 @@ export class App {
});
const authProvider = new AzureIdentityAuthenticationProvider(cred, ['Mail.Read']);
const requestAdapter = new FetchRequestAdapter(authProvider);
const client = new ApiClient(requestAdapter);
const client = createApiClient(requestAdapter);
Logger.log(`${client}`);
return app;
}
Expand Down
18 changes: 17 additions & 1 deletion src/Kiota.Builder/Refiners/TypeScriptRefiner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1103,9 +1103,25 @@ protected static void AddEnumObject(CodeElement currentElement)
}
CrawlTree(currentElement, AddEnumObject);
}

protected static void AddEnumObjectUsings(CodeElement currentElement)
{
if (currentElement is CodeProperty codeProperty && codeProperty.Kind is CodePropertyKind.RequestBuilder && codeProperty.Type is CodeType codeType && codeType.TypeDefinition is CodeClass codeClass)
{
foreach (var propertyMethod in codeClass.Methods)
{
if (propertyMethod.ReturnType is CodeType ct && ct.TypeDefinition is CodeEnum codeEnum)
{
codeClass.AddUsing(new CodeUsing
{
Name = codeEnum.Name,
Declaration = new CodeType
{
TypeDefinition = codeEnum.CodeEnumObject
}
});
}
}
}
if (currentElement is CodeFunction codeFunction && codeFunction.OriginalLocalMethod.IsOfKind(CodeMethodKind.Deserializer, CodeMethodKind.Serializer))
{
foreach (var propertyEnum in codeFunction.OriginalMethodParentClass.Properties.Select(static x => x.Type).OfType<CodeType>().Select(static x => x.TypeDefinition).OfType<CodeEnum>())
Expand Down
9 changes: 8 additions & 1 deletion src/Kiota.Builder/Writers/TypeScript/CodeConstantWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,14 @@ private void WriteRequestsMetadataConstant(CodeConstant codeElement, LanguageWri
}
writer.WriteLine($"adapterMethodName: \"{GetSendRequestMethodName(isVoid, isStream, executorMethod.ReturnType.IsCollection, isPrimitive, isEnum)}\",");
if (isEnum)
writer.WriteLine($"enumObject: {executorMethod.ReturnType.Name.ToFirstCharacterUpperCase()},");
{
string enumObjectName = string.Empty;
if (executorMethod.ReturnType is CodeType ct && ct.TypeDefinition is CodeEnum ce)
{
enumObjectName = ce.CodeEnumObject!.Name;
}
writer.WriteLine($"enumObject: {enumObjectName!.ToFirstCharacterUpperCase()},");
}
else if (!isVoid)
writer.WriteLine($"responseBodyFactory: {GetTypeFactory(isVoid, isStream, executorMethod, writer)},");
var sanitizedRequestBodyContentType = executorMethod.RequestBodyContentType.SanitizeDoubleQuote();
Expand Down
29 changes: 29 additions & 0 deletions tests/Kiota.Builder.IntegrationTests/EnumHandling.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
openapi: 3.0.3
info:
title: Test
version: 3.0.x
description: Testing enum handling.
license:
name: Apache 2.0
url: https://www.apache.org/licenses/LICENSE-2.0
paths:
"/play":
get:
responses:
"200":
content:
application/json:
schema:
"$ref": "#/components/schemas/MoveType"
description: A move
description: "Play a move"
components:
schemas:
MoveType:
description: ""
enum:
- ROCK
- PAPER
- SCISSORS
type: string
example: ROCK
22 changes: 22 additions & 0 deletions tests/Kiota.Builder.IntegrationTests/GenerateSample.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,28 @@ public async Task GeneratesErrorsInliningParents(GenerationLanguage language)
};
await new KiotaBuilder(logger, configuration, _httpClient).GenerateClientAsync(new());
}
[InlineData(GenerationLanguage.CSharp)]
[InlineData(GenerationLanguage.Java)]
[InlineData(GenerationLanguage.Go)]
[InlineData(GenerationLanguage.Ruby)]
[InlineData(GenerationLanguage.Python)]
[InlineData(GenerationLanguage.TypeScript)]
[InlineData(GenerationLanguage.PHP)]
[Theory]
public async Task GeneratesCorrectEnums(GenerationLanguage language)
{
var logger = LoggerFactory.Create(builder =>
{
}).CreateLogger<KiotaBuilder>();

var configuration = new GenerationConfiguration
{
Language = language,
OpenAPIFilePath = GetAbsolutePath("EnumHandling.yaml"),
OutputPath = $".\\Generated\\EnumHandling\\{language}",
};
await new KiotaBuilder(logger, configuration, _httpClient).GenerateClientAsync(new());
}
[InlineData(GenerationLanguage.Java)]
[Theory]
public async Task GeneratesIdiomaticChildrenNames(GenerationLanguage language)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@
<None Update="GeneratesUritemplateHints.yaml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="EnumHandling.yaml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>

0 comments on commit bf2f42c

Please sign in to comment.