Skip to content

Commit 88b9bd6

Browse files
authored
fix: use default value when deserializing non-optional members (#436)
Codegen uses default values to generate the `init` for non-optional values eg. https://github.com/awslabs/aws-sdk-swift/blob/0.2.6/release/AWSSecretsManager/models/Models.swift#L4148 but while doing the deserialization, the member is considered as always present which is not true in service like AWSSecretsManager. This change uses the the same default value is available to set the member when the response doesn't contain the field. To generate less code, codegen skips assigning nil. Before ``` let rotationEnabledDecoded = try containerValues.decode(Swift.Bool.self, forKey: .rotationEnabled) rotationEnabled = rotationEnabledDecoded ``` After ``` let rotationEnabledDecoded = try containerValues.decodeIfPresent(Swift.Bool.self, forKey: .rotationEnabled) ?? false rotationEnabled = rotationEnabledDecoded ```
1 parent ba46351 commit 88b9bd6

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

smithy-swift-codegen/src/main/kotlin/software/amazon/smithy/swift/codegen/integration/serde/json/MemberShapeDecodeGenerator.kt

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import software.amazon.smithy.swift.codegen.SwiftWriter
2020
import software.amazon.smithy.swift.codegen.customtraits.SwiftBoxTrait
2121
import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator
2222
import software.amazon.smithy.swift.codegen.integration.serde.MemberShapeDecodeGeneratable
23+
import software.amazon.smithy.swift.codegen.model.defaultValue
2324
import software.amazon.smithy.swift.codegen.model.hasTrait
2425
import software.amazon.smithy.swift.codegen.model.isBoxed
2526
import software.amazon.smithy.swift.codegen.model.recursiveSymbol
@@ -63,9 +64,14 @@ abstract class MemberShapeDecodeGenerator(
6364
if (member.hasTrait(SwiftBoxTrait::class.java)) {
6465
symbol = symbol.recursiveSymbol()
6566
}
66-
val decodeVerb = if (symbol.isBoxed()) "decodeIfPresent" else "decode"
67+
val defaultValue = symbol.defaultValue()
68+
val decodeVerb = if (symbol.isBoxed() || !defaultValue.isNullOrEmpty()) "decodeIfPresent" else "decode"
6769
val decodedMemberName = "${memberName}Decoded"
68-
writer.write("let \$L = try \$L.$decodeVerb(\$N.self, forKey: .\$L)", decodedMemberName, containerName, symbol, memberName)
70+
71+
// no need to assign nil to a member that is optional
72+
val defaultValueLiteral = if (defaultValue != null && defaultValue != "nil") " ?? $defaultValue" else ""
73+
74+
writer.write("let \$L = try \$L.$decodeVerb(\$N.self, forKey: .\$L)$defaultValueLiteral", decodedMemberName, containerName, symbol, memberName)
6975
renderAssigningDecodedMember(member, decodedMemberName)
7076
}
7177

0 commit comments

Comments
 (0)