Skip to content

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
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions Sources/AWSLambdaEvents/APIGateway+V2.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
//
//===----------------------------------------------------------------------===//

import Foundation

extension APIGateway {
public struct V2 {}
}
Expand Down Expand Up @@ -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? {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rename Payload -> Body

Copy link
Contributor

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 like decoder: (Body) -> String and have a default impl that uses JSONDecoder

Copy link
Contributor

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 enough

Copy link
Contributor Author

@eneko eneko Jun 16, 2020

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 the body property. Will update.

Copy link
Contributor Author

@eneko eneko Jun 16, 2020

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:

public func decodedBody<Body: Codable>(decoder: (String.UTF8View) throws -> Body) throws -> Body? {
    guard let utf8 = body?.utf8 else {
        return nil
    }
    return try decoder(utf8)
}

And what the callee would look like:

let decoder: (String.UTF8View) throws -> Body = { utf8 in try JSONDecoder().decode(Body.self, from: Data(utf8)) }
let body: Body? = try request.decodedBody(decoder: decoder)

At that point, using this extension would yield close to no benefit.

Copy link
Contributor

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):

public func decodedBody<Body: Decodable>(decoder: @escaping (String) throws -> Body = Self.jsonDecoder) throws -> Body? {
  try self.body.map(decoder)
}
        
public static func jsonDecoder<T: Decodable>(json: String) throws -> T {
  try JSONDecoder().decode(T.self, from: Data(json.utf8))
}

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>(
Copy link
Contributor

Choose a reason for hiding this comment

The 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()
Copy link
Contributor

Choose a reason for hiding this comment

The 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)
}
}
36 changes: 34 additions & 2 deletions Tests/AWSLambdaEventsTests/APIGateway+V2Tests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 {
Copy link
Contributor

Choose a reason for hiding this comment

The 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)
}

}