Skip to content

Commit 3048743

Browse files
handle base64-encoded request bodies (#10)
1 parent af9ea32 commit 3048743

File tree

3 files changed

+48
-2
lines changed

3 files changed

+48
-2
lines changed

Sources/Vercel/InvokeEvent.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ public struct InvokeEvent: Codable, Sendable {
1313
public let headers: HTTPHeaders
1414
public let path: String
1515
public let body: String?
16+
public let encoding: String?
1617
}
1718

1819
public let body: String

Sources/Vercel/Request.swift

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,30 @@ public struct Request: Sendable {
1010
public let headers: HTTPHeaders
1111
public let path: String
1212
public let searchParams: [String: String]
13-
public let body: String?
13+
public let rawBody: Data?
1414

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

18+
public var body: String? {
19+
if let rawBody = rawBody {
20+
return String(bytes: rawBody, encoding: .utf8)
21+
}
22+
23+
return nil
24+
}
25+
1826
internal init(_ payload: InvokeEvent.Payload) {
1927
self.method = payload.method
2028
self.headers = payload.headers
2129
self.path = payload.path
22-
self.body = payload.body
30+
31+
if let encoding = payload.encoding, let body = payload.body, encoding == "base64" {
32+
rawBody = Data(base64Encoded: body)
33+
} else {
34+
rawBody = payload.body?.data(using: .utf8)
35+
}
36+
2337
self.searchParams = URLComponents(string: payload.path)?
2438
.queryItems?
2539
.reduce(into: [:]) { $0[$1.name] = $1.value } ?? [:]

Tests/VercelTests/RequestTests.swift

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,35 @@ final class RequestTests: XCTestCase {
4646
XCTAssertEqual(req.method, .GET)
4747
XCTAssertEqual(req.searchParams["token"], "12345")
4848
}
49+
50+
func testPlainBody() throws {
51+
let json = """
52+
{
53+
"method": "PUT",
54+
"path": "/",
55+
"headers": {},
56+
"body": "hello"
57+
}
58+
"""
59+
let payload = try JSONDecoder().decode(InvokeEvent.Payload.self, from: json.data(using: .utf8)!)
60+
let req = Request(payload)
61+
XCTAssertEqual(req.body, "hello")
62+
}
63+
64+
func testBase64Body() throws {
65+
let json = """
66+
{
67+
"method": "PUT",
68+
"path": "/",
69+
"headers": {},
70+
"body": "/////w==",
71+
"encoding": "base64"
72+
}
73+
"""
74+
let payload = try JSONDecoder().decode(InvokeEvent.Payload.self, from: json.data(using: .utf8)!)
75+
let req = Request(payload)
76+
let expectData: [UInt8] = [0xff, 0xff, 0xff, 0xff]
77+
XCTAssertEqual(req.rawBody, Data(expectData))
78+
XCTAssertNil(req.body)
79+
}
4980
}

0 commit comments

Comments
 (0)