-
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
Closed
Closed
Changes from 3 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
9abd4f9
Add APIGateway+V2+JSON
eneko b01b5e6
Provide extensions to decode and encode API Gateway V2 payloads
eneko ae03de0
Unit tests for payload coding/decoding
eneko bb688c4
Inject encoder and decoder
eneko 7885a21
Merge branch 'master' into feature/codable-api-gateway-v2
eneko f24463b
PR Feedback. Fix tests.
eneko fda00d9
Merge branch 'feature/codable-api-gateway-v2' of https://github.com/e…
eneko 536630d
Merge branch 'master' into feature/codable-api-gateway-v2
eneko File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -12,6 +12,8 @@ | |
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
import Foundation | ||
|
||
extension APIGateway { | ||
public struct V2 {} | ||
} | ||
|
@@ -117,3 +119,79 @@ 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>() throws -> Payload? { | ||
guard let bodyString = body else { | ||
return nil | ||
} | ||
let data = Data(bodyString.utf8) | ||
return try JSONDecoder().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 | ||
) throws { | ||
let data = try JSONEncoder().encode(body) | ||
let bodyString = String(data: data, encoding: .utf8) | ||
self.init(statusCode: statusCode, | ||
headers: headers, | ||
multiValueHeaders: multiValueHeaders, | ||
body: bodyString, | ||
isBase64Encoded: false, | ||
cookies: cookies) | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
|
||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
how about:
public func decodedBody<Payload: Codable>(decoder:JSONDecoder = JSONDecoder()) throws -> Payload? {
This way the user has can customize the decoder and provide their own. For example, to change the dateDecodingStrategy.
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.
(Same suggestion for the JSONEncoder usage below)
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.
That's a good point but also yet another instance where "TopLevelDecoder" types would be the right thing to go with... Since we'd like to allow using various coder implementations, not marry the API to Foundation's impl only.
We could do them ad-hoc here in the lambda lib again as Combine does, but that's growing the problem a bit; Or we ignore and go along with this for now, but eventually try to resolve it once we get to it.
// fyi @tomerd
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.
Thanks for the feedback. I've updated the PR to inject both
JSONEncoder
andJSONDecoder
.I agree a "TopLevelDecoder" type would be ideal, let me know if I should do any further changes.
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.
Another idea would be to see if it's possible to push the functions out into an "AWSLambdaFoundationCompat" module or something similar?
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.
@ktoso I was looking at
Lambda+Codable.swift
fromAWSLambdaRuntime
and it seems like encoding/decoding work could be moved to a separate module, like you suggest. I haven't tried it, though.Would you be open for that work being done on a separate pull request? While I think it is valuable, it feels out of the initial scope of this work.
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.
Sorry, I don't know the internals here, based on a github search I don't see too many instances of "import Foundation". Would that mean that the lambda runtime wouldn't depend on
Foundation
? That might be nice for performance, right?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.
@calcohen, at the moment, yes,
AWSLambdaRuntime
depends onFoundation
forCodable
support:swift-aws-lambda-runtime/Sources/AWSLambdaRuntime/Lambda+Codable.swift
Line 17 in 246088e
It might be possible to remove this dependency, like @ktoso suggested, but to me that feels like work for a different pull request.