Skip to content

Commit 70b65d3

Browse files
authored
feat: Use JsonPropertyOrder attribute (#36)
1 parent cf1b7b0 commit 70b65d3

File tree

3 files changed

+25
-2
lines changed

3 files changed

+25
-2
lines changed

demo/APIWeaver.MinimalApi.Demo/Program.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868

6969
public class User
7070
{
71+
7172
private int _number;
7273
public required string Id { get; set; }
7374

@@ -79,6 +80,7 @@ public class User
7980
[JsonInclude]
8081
private string FullName { get; init; } = "awd";
8182

83+
[JsonPropertyOrder(1)]
8284
public int Number
8385
{
8486
set => _number = value;

src/APIWeaver.Schema/Factories/ContractFactory.cs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,10 +57,14 @@ public IContract GetContract(Type type, IEnumerable<Attribute> customAttributes)
5757

5858
private IEnumerable<PropertyContract> GetProperties(Type type)
5959
{
60-
var properties = GetPropertyContractsFromProperties(type);
6160
var fields = GetPropertyContractsFromFields(type);
61+
var properties = GetPropertyContractsFromProperties(type);
6262

63-
return properties.Concat(fields);
63+
return fields.Concat(properties).OrderBy(property =>
64+
{
65+
var orderAttribute = property.CustomAttributes.OfType<JsonPropertyOrderAttribute>().FirstOrDefault();
66+
return orderAttribute?.Order ?? int.MaxValue;
67+
});
6468
}
6569

6670
private IEnumerable<PropertyContract> GetPropertyContractsFromProperties(Type type)

tests/APIWeaver.Schema.Tests/ContractFactoryTests.cs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,22 @@ public void GetContract_ShouldIgnoreReadOnlyProperties_WhenOptionsSet()
331331
properties.Should().NotContain(x => x.Name == "fullName");
332332
properties.Should().NotContain(x => x.Name == "theAge");
333333
}
334+
335+
[Fact]
336+
public void GetContract_ShouldReturnPropertyWithOrderAttributeFirst_WhenPropertyHasOrderAttribute()
337+
{
338+
// Arrange
339+
var type = typeof(UserForProperties);
340+
341+
// Act
342+
var contract = _sut.GetContract(type, []);
343+
344+
// Assert
345+
contract.Should().BeOfType<ObjectTypeContract>()
346+
.Which.Type.Should().Be(type);
347+
var properties = (contract as ObjectTypeContract)!.Properties.ToArray();
348+
properties[0].Name.Should().Be("fullName");
349+
}
334350
}
335351

336352
[JsonConverter(typeof(JsonStringEnumConverter))]
@@ -362,6 +378,7 @@ file class UserForProperties
362378
private string? Name { get; init; }
363379

364380
[JsonInclude]
381+
[JsonPropertyOrder(1)]
365382
private string FullName { get; } = null!;
366383
}
367384
#pragma warning restore CS0649 // Field is never assigned to, and will always have its default value

0 commit comments

Comments
 (0)