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

Add support for kebab-string-casing parameters #11

Merged
merged 5 commits into from
Mar 22, 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
8 changes: 4 additions & 4 deletions src/Refitter.Core/ParameterExtractor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,22 @@ public static IEnumerable<string> GetParameters(CSharpClientGenerator generator,
{
var routeParameters = operation.ActualParameters
.Where(p => p.Kind == OpenApiParameterKind.Path)
.Select(p => $"{generator.GetTypeName(p.ActualTypeSchema, true, null)} {p.Name}")
.Select(p => $"{generator.GetTypeName(p.ActualTypeSchema, true, null)} {p.Name.ConvertKebabCaseToCamelCase()}")
.ToList();

var queryParameters = operation.Parameters
.Where(p => p.Kind == OpenApiParameterKind.Query)
.Select(p => $"[Query(CollectionFormat.Multi)]{GetBodyParameterType(generator, p)} {p.Name}")
.Select(p => $"[Query(CollectionFormat.Multi)]{GetBodyParameterType(generator, p)} {p.Name.ConvertKebabCaseToCamelCase()}")
.ToList();

var bodyParameters = operation.Parameters
.Where(p => p.Kind == OpenApiParameterKind.Body && !p.IsBinaryBodyParameter)
.Select(p => $"[Body]{GetBodyParameterType(generator, p)} {p.Name}")
.Select(p => $"[Body]{GetBodyParameterType(generator, p)} {p.Name.ConvertKebabCaseToCamelCase()}")
.ToList();

var multipartFormParameters = operation.Parameters
.Where(p => p.Kind == OpenApiParameterKind.Body && p.IsBinaryBodyParameter)
.Select(p => $"[Body(BodySerializationMethod.UrlEncoded)] Dictionary<string, object> {p.Name}")
.Select(p => $"[Body(BodySerializationMethod.UrlEncoded)] Dictionary<string, object> {p.Name.ConvertKebabCaseToCamelCase()}")
.ToList();

var parameters = new List<string>();
Expand Down
2 changes: 1 addition & 1 deletion src/Refitter.Core/RefitInterfaceGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ private string GenerateInterfaceBody()

GenerateMethodXmlDocComments(operation, code);

code.AppendLine($"{Separator}{Separator}[{verb}(\"{kv.Key}\")]")
code.AppendLine($"{Separator}{Separator}[{verb}(\"{kv.Key.ConvertKebabCaseToCamelCase()}\")]")
.AppendLine($"{Separator}{Separator}{returnType} {name}({parametersString});")
.AppendLine();
}
Expand Down
11 changes: 11 additions & 0 deletions src/Refitter.Core/StringCasingExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,17 @@ public static string ConvertKebabCaseToPascalCase(this string str)

return string.Join(string.Empty, parts);
}

public static string ConvertKebabCaseToCamelCase(this string str)
{
var parts = str.Split('-');
for (var i = 1; i < parts.Length; i++)
{
parts[i] = parts[i].CapitalizeFirstCharacter();
}

return string.Join(string.Empty, parts);
}

public static string CapitalizeFirstCharacter(this string str)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System.Diagnostics;

namespace Refitter.Tests;
namespace Refitter.Tests.Build;

public static class BuildHelper
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace Refitter.Tests;
namespace Refitter.Tests.Build;

public static class ProjectFileContents
{
Expand Down
96 changes: 96 additions & 0 deletions src/Refitter.Tests/KebabCaseTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
using FluentAssertions;
using Refitter.Core;
using Refitter.Tests.Build;
using Xunit;

namespace Refitter.Tests;

public class KebabCaseTests
{
private const string OpenApiSpec = @"
openapi: '3.0.0'
info:
version: 'v1'
title: 'Test API'
servers:
- url: 'https://test.host.com/api/v1'
paths:
/jobs/{job-id}:
get:
tags:
- 'Jobs'
summary: 'Get job details'
description: 'Get the details of the specified job.'
parameters:
- in: 'path'
name: 'job-id'
description: 'Job ID'
required: true
schema:
type: 'string'
responses:
'200':
description: 'successful operation'
content:
application/json:
schema:
$ref: '#/components/schemas/JobResponse'
components:
schemas:
JobResponse:
type: 'object'
properties:
job:
type: 'object'
properties:
start-date:
type: 'string'
format: 'date-time'
details:
type: 'string'
";

[Fact]
public async Task Can_Generate_Code()
{
string generateCode = await GenerateCode();
generateCode.Should().NotBeNullOrWhiteSpace();
}

[Fact]
public async Task Replaces_KababCase_Parameters_With_PascalCase()
{
string generateCode = await GenerateCode();
generateCode.Should().Contain("string jobId");
}

[Fact]
public async Task Can_Build_Generated_Code()
{
string generateCode = await GenerateCode();
BuildHelper
.BuildCSharp(generateCode)
.Should()
.BeTrue();
}

private static async Task<string> GenerateCode()
{
var swaggerFile = await CreateSwaggerFile(OpenApiSpec);
var settings = new RefitGeneratorSettings { OpenApiPath = swaggerFile };

var sut = await RefitGenerator.CreateAsync(settings);
var generateCode = sut.Generate();
return generateCode;
}

private static async Task<string> CreateSwaggerFile(string contents)
{
var filename = $"{Guid.NewGuid()}.yml";
var folder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(folder);
var swaggerFile = Path.Combine(folder, filename);
await File.WriteAllTextAsync(swaggerFile, contents);
return swaggerFile;
}
}
101 changes: 101 additions & 0 deletions src/Refitter.Tests/PathParametersTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
using FluentAssertions;
using FluentAssertions.Execution;
using Refitter.Core;
using Refitter.Tests.Build;
using Xunit;

namespace Refitter.Tests;

public class PathParametersTests
{
private const string OpenApiSpec = @"
swagger: '2.0'
info:
title: Reference parameters
version: v0.0.1
paths:
'/orders/{orderId}/order-items/{orderItemId}':
parameters:
- $ref: '#/parameters/OrderId'
- $ref: '#/parameters/OrderItemId'
delete:
summary: Delete an order item
description: >-
This method allows to remove an order item from an order, by specifying
their ids.
responses:
'204':
description: No Content.
default:
description: Default response
schema:
$ref: '#/definitions/Error'
definitions:
Error:
type: object
properties:
message:
type: string
parameters:
OrderId:
name: orderId
in: path
description: Identifier of the order.
required: true
type: string
format: uuid
OrderItemId:
name: orderItemId
in: path
description: Identifier of the order item.
required: true
type: string
format: uuid
";

[Fact]
public async Task Can_Generate_Code()
{
var generateCode = await GenerateCode();
generateCode.Should().NotBeNullOrWhiteSpace();
}

[Fact]
public async Task Generates_Path_Parameters()
{
var generateCode = await GenerateCode();
using var scope = new AssertionScope();
generateCode.Should().Contain("Guid? orderId");
generateCode.Should().Contain("Guid? orderItemId");
}

[Fact]
public async Task Can_Build_Generated_Code()
{
var generateCode = await GenerateCode();
BuildHelper
.BuildCSharp(generateCode)
.Should()
.BeTrue();
}

private static async Task<string> GenerateCode()
{
var swaggerFile = await CreateSwaggerFile(OpenApiSpec);
var settings = new RefitGeneratorSettings { OpenApiPath = swaggerFile };

var sut = await RefitGenerator.CreateAsync(settings);
var generateCode = sut.Generate();
return generateCode;
}

private static async Task<string> CreateSwaggerFile(string contents)
{
var filename = $"{Guid.NewGuid()}.yml";
var folder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(folder);
var swaggerFile = Path.Combine(folder, filename);
await File.WriteAllTextAsync(swaggerFile, contents);
return swaggerFile;
}
}
1 change: 1 addition & 0 deletions src/Refitter.Tests/RefitGeneratorTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using FluentAssertions;
using Refitter.Core;
using Refitter.Tests.Build;
using Refitter.Tests.Resources;
using Xunit;

Expand Down
23 changes: 23 additions & 0 deletions src/Refitter.Tests/StringCasingExtensionTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using FluentAssertions;
using Refitter.Core;
using Xunit;

namespace Refitter.Tests;

public class StringCasingExtensionTests
{
[Theory]
[InlineData("some-string", "SomeString")]
public void CanConvertToPascalCase(string input, string expected)
=> input.ConvertKebabCaseToPascalCase().Should().Be(expected);

[Theory]
[InlineData("some-string", "someString")]
public void CanConvertToCamelCase(string input, string expected)
=> input.ConvertKebabCaseToCamelCase().Should().Be(expected);

[Theory]
[InlineData("abcd", "Abcd")]
public void CanCaptilalizeFirstLetter(string input, string expected)
=> input.CapitalizeFirstCharacter().Should().Be(expected);
}