-
Notifications
You must be signed in to change notification settings - Fork 113
Codable support for APIGateway V2 request and response payloads #129
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
Changes from 5 commits
9abd4f9
b01b5e6
ae03de0
bb688c4
7885a21
f24463b
fda00d9
536630d
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 |
---|---|---|
|
@@ -12,6 +12,8 @@ | |
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
import Foundation | ||
|
||
extension APIGateway { | ||
public struct V2 {} | ||
} | ||
|
@@ -117,3 +119,80 @@ extension APIGateway.V2 { | |
} | ||
} | ||
} | ||
|
||
// MARK: - Codable Request body | ||
|
||
extension APIGateway.V2.Request { | ||
/// Generic body decoder for JSON payloads | ||
/// | ||
/// Example: | ||
/// ``` | ||
/// struct Request: Codable { | ||
/// let value: String | ||
/// } | ||
/// | ||
/// func handle(context: Context, event: APIGateway.V2.Request, callback: @escaping (Result<APIGateway.V2.Response, Error>) -> Void) { | ||
/// do { | ||
/// let request: Request? = try event.decodedBody() | ||
/// // Do something with `request` | ||
/// callback(.success(APIGateway.V2.Response(statusCode: .ok, body:""))) | ||
/// } | ||
/// catch { | ||
/// callback(.failure(error)) | ||
/// } | ||
/// } | ||
/// ``` | ||
/// | ||
/// - Throws: `DecodingError` if body contains a value that couldn't be decoded | ||
/// - Returns: Decoded payload. Returns `nil` if body property is `nil`. | ||
public func decodedBody<Payload: Codable>(decoder: JSONDecoder = JSONDecoder()) throws -> Payload? { | ||
guard let bodyString = body else { | ||
return nil | ||
} | ||
let data = Data(bodyString.utf8) | ||
return try decoder.decode(Payload.self, from: data) | ||
} | ||
} | ||
|
||
// MARK: - Codable Response body | ||
|
||
extension APIGateway.V2.Response { | ||
/// Codable initializer for Response payload | ||
/// | ||
/// Example: | ||
/// ``` | ||
/// struct Response: Codable { | ||
/// let message: String | ||
/// } | ||
/// | ||
/// func handle(context: Context, event: APIGateway.V2.Request, callback: @escaping (Result<APIGateway.V2.Response, Error>) -> Void) { | ||
/// ... | ||
/// callback(.success(APIGateway.V2.Response(statusCode: .ok, body: Response(message: "Hello, World!"))) | ||
/// } | ||
/// ``` | ||
/// | ||
/// - Parameters: | ||
/// - statusCode: Response HTTP status code | ||
/// - headers: Response HTTP headers | ||
/// - multiValueHeaders: Resposne multi-value headers | ||
/// - body: `Codable` response payload | ||
/// - cookies: Response cookies | ||
/// - Throws: `EncodingError` if payload could not be encoded into a JSON string | ||
public init<Payload: Codable>( | ||
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. rename Payload -> Body |
||
statusCode: HTTPResponseStatus, | ||
headers: HTTPHeaders? = nil, | ||
multiValueHeaders: HTTPMultiValueHeaders? = nil, | ||
body: Payload? = nil, | ||
cookies: [String]? = nil, | ||
encoder: JSONEncoder = JSONEncoder() | ||
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. tbd.. same comment like the decoder above |
||
) throws { | ||
let data = try encoder.encode(body) | ||
let bodyString = String(data: data, encoding: .utf8) | ||
self.init(statusCode: statusCode, | ||
headers: headers, | ||
multiValueHeaders: multiValueHeaders, | ||
body: bodyString, | ||
isBase64Encoded: false, | ||
cookies: cookies) | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -68,10 +68,15 @@ class APIGatewayV2Tests: XCTestCase { | |
"x-amzn-trace-id":"Root=1-5ea3263d-07c5d5ddfd0788bed7dad831", | ||
"user-agent":"Paw/3.1.10 (Macintosh; OS X/10.15.4) GCDHTTPRequest", | ||
"content-length":"0" | ||
} | ||
}, | ||
"body": "{\\"some\\":\\"json\\",\\"number\\":42}" | ||
} | ||
""" | ||
|
||
static let exampleResponse = """ | ||
{"isBase64Encoded":false,"statusCode":200,"body":"{\\"message\\":\\"Foo Bar\\",\\"code\\":42}"} | ||
""" | ||
|
||
// MARK: - Request - | ||
|
||
// MARK: Decoding | ||
|
@@ -86,6 +91,33 @@ class APIGatewayV2Tests: XCTestCase { | |
XCTAssertEqual(req?.queryStringParameters?.count, 1) | ||
XCTAssertEqual(req?.rawQueryString, "foo=bar") | ||
XCTAssertEqual(req?.headers.count, 8) | ||
XCTAssertNil(req?.body) | ||
XCTAssertNotNil(req?.body) | ||
} | ||
|
||
func testRquestPayloadDecoding() throws { | ||
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. typo |
||
struct Payload: Codable { | ||
let some: String | ||
let number: Int | ||
} | ||
|
||
let data = APIGatewayV2Tests.exampleGetEventBody.data(using: .utf8)! | ||
let request = try JSONDecoder().decode(APIGateway.V2.Request.self, from: data) | ||
|
||
let payload: Payload? = try request.decodedBody() | ||
XCTAssertEqual(payload?.some, "json") | ||
XCTAssertEqual(payload?.number, 42) | ||
} | ||
|
||
func testResponsePayloadEncoding() throws { | ||
struct Payload: Codable { | ||
let code: Int | ||
let message: String | ||
} | ||
|
||
let response = try APIGateway.V2.Response(statusCode: .ok, body: Payload(code: 42, message: "Foo Bar")) | ||
let data = try JSONEncoder().encode(response) | ||
let json = String(data: data, encoding: .utf8) | ||
XCTAssertEqual(json, APIGatewayV2Tests.exampleResponse) | ||
} | ||
|
||
} |
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.
rename Payload -> Body
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.
I wonder if instead of
decoder: JSONDecoder = JSONDecoder()
which should do something likedecoder: (Body) -> String
and have a default impl that uses JSONDecoderThere 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.
following on that line of thinking, @fabianfett maybe knows if this should be
(Body) ->[UInt8]
, or String is good enoughUh oh!
There was an error while loading. Please reload this page.
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.
The decoder should be either
(String) throws -> Body
or(String.UTF8View) throws -> Body
, since we are decoding the content of thebody
property. Will update.Uh oh!
There was an error while loading. Please reload this page.
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.
I've given this a shot, but kind of defeats the purpose of the pull request.
Here is what the extension would look like:
And what the callee would look like:
At that point, using this extension would yield close to no benefit.
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.
@eneko I meant the library would offer a default impl as well, for example (non optimized):