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 all 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 decoder for JSON body
///
/// Example:
/// ```
/// struct Body: Codable {
/// let value: String
/// }
///
/// func handle(context: Context, event: APIGateway.V2.Request, callback: @escaping (Result<APIGateway.V2.Response, Error>) -> Void) {
/// do {
/// let body: Body? = try event.decodedBody()
/// // Do something with `body`
/// 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 body. Returns `nil` if body property is `nil`.
public func decodedBody<Body: Codable>(decoder: JSONDecoder = JSONDecoder()) throws -> Body? {
guard let bodyString = body else {
return nil
}
let data = Data(bodyString.utf8)
return try decoder.decode(Body.self, from: data)
}
}

// MARK: - Codable Response body

extension APIGateway.V2.Response {
/// Codable initializer for Response body
///
/// 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 body
/// - cookies: Response cookies
/// - Throws: `EncodingError` if body could not be encoded into a JSON string
public init<Body: Codable>(
statusCode: HTTPResponseStatus,
headers: HTTPHeaders? = nil,
multiValueHeaders: HTTPMultiValueHeaders? = nil,
body: Body? = 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)
}
}
37 changes: 35 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 exampleResponseBody = """
{\"code\":42,\"message\":\"Foo Bar\"}
"""

// MARK: - Request -

// MARK: Decoding
Expand All @@ -86,6 +91,34 @@ 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 testRequestBodyDecoding() throws {
struct Body: 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 body: Body? = try request.decodedBody()
XCTAssertEqual(body?.some, "json")
XCTAssertEqual(body?.number, 42)
}

func testResponseBodyEncoding() throws {
struct Body: Codable {
let code: Int
let message: String
}

let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
let body = Body(code: 42, message: "Foo Bar")
let response = try APIGateway.V2.Response(statusCode: .ok, body: body, encoder: encoder)
XCTAssertEqual(response.body, APIGatewayV2Tests.exampleResponseBody)
}

}