-
Notifications
You must be signed in to change notification settings - Fork 47
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
Fix encoding of plain text bodies #9
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -90,7 +90,18 @@ extension Converter { | |
from data: Data, | ||
transforming transform: (T) -> C | ||
) throws -> C { | ||
let decoded = try decoder.decode(type, from: data) | ||
let decoded: T | ||
if let myType = T.self as? _StringParameterConvertible.Type { | ||
guard | ||
let stringValue = String(data: data, encoding: .utf8), | ||
let decodedValue = myType.init(stringValue) | ||
else { | ||
throw RuntimeError.failedToDecodePrimitiveBodyFromData | ||
} | ||
decoded = decodedValue as! T | ||
} else { | ||
decoded = try decoder.decode(type, from: data) | ||
} | ||
czechboy0 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return transform(decoded) | ||
} | ||
|
||
|
@@ -128,6 +139,12 @@ extension Converter { | |
) throws -> Data { | ||
let body = transform(value) | ||
headerFields.add(name: "content-type", value: body.contentType) | ||
if let value = value as? _StringParameterConvertible { | ||
guard let data = value.description.data(using: .utf8) else { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same here, the correct and fast way is There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
throw RuntimeError.failedToEncodePrimitiveBodyIntoData | ||
} | ||
return data | ||
} | ||
return try encoder.encode(body.value) | ||
} | ||
|
||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please avoid String(data:encoding:), especially in networked software as it has 2 failure modes (return nil or insert replacement characters for invalid UTF8 -- which one it chooses depends on what's broken).
The correct and faster way is
String(decoding: data, as: UTF8.self)
which also doesn't require Foundation and is not fallibleThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks, broke out into apple/swift-openapi-generator#42