Skip to content

Commit

Permalink
handle base64-encoded request bodies (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
summertriangle-dev authored May 30, 2023
1 parent af9ea32 commit 3048743
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 2 deletions.
1 change: 1 addition & 0 deletions Sources/Vercel/InvokeEvent.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ public struct InvokeEvent: Codable, Sendable {
public let headers: HTTPHeaders
public let path: String
public let body: String?
public let encoding: String?
}

public let body: String
Expand Down
18 changes: 16 additions & 2 deletions Sources/Vercel/Request.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,30 @@ public struct Request: Sendable {
public let headers: HTTPHeaders
public let path: String
public let searchParams: [String: String]
public let body: String?
public let rawBody: Data?

/// Private instance var to prevent decodable from failing
public internal(set) var pathParams: Parameters = .init()

public var body: String? {
if let rawBody = rawBody {
return String(bytes: rawBody, encoding: .utf8)
}

return nil
}

internal init(_ payload: InvokeEvent.Payload) {
self.method = payload.method
self.headers = payload.headers
self.path = payload.path
self.body = payload.body

if let encoding = payload.encoding, let body = payload.body, encoding == "base64" {
rawBody = Data(base64Encoded: body)
} else {
rawBody = payload.body?.data(using: .utf8)
}

self.searchParams = URLComponents(string: payload.path)?
.queryItems?
.reduce(into: [:]) { $0[$1.name] = $1.value } ?? [:]
Expand Down
31 changes: 31 additions & 0 deletions Tests/VercelTests/RequestTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,35 @@ final class RequestTests: XCTestCase {
XCTAssertEqual(req.method, .GET)
XCTAssertEqual(req.searchParams["token"], "12345")
}

func testPlainBody() throws {
let json = """
{
"method": "PUT",
"path": "/",
"headers": {},
"body": "hello"
}
"""
let payload = try JSONDecoder().decode(InvokeEvent.Payload.self, from: json.data(using: .utf8)!)
let req = Request(payload)
XCTAssertEqual(req.body, "hello")
}

func testBase64Body() throws {
let json = """
{
"method": "PUT",
"path": "/",
"headers": {},
"body": "/////w==",
"encoding": "base64"
}
"""
let payload = try JSONDecoder().decode(InvokeEvent.Payload.self, from: json.data(using: .utf8)!)
let req = Request(payload)
let expectData: [UInt8] = [0xff, 0xff, 0xff, 0xff]
XCTAssertEqual(req.rawBody, Data(expectData))
XCTAssertNil(req.body)
}
}

0 comments on commit 3048743

Please sign in to comment.