Skip to content

Commit

Permalink
fix(functions): functions overrides headers (#160)
Browse files Browse the repository at this point in the history
  • Loading branch information
grdsdev authored Nov 15, 2023
1 parent 6b918c3 commit e8ba6d1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
10 changes: 5 additions & 5 deletions Sources/Functions/Types.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,23 +34,23 @@ public struct FunctionInvokeOptions {
/// - headers: Headers to be included in the function invocation. (Default: empty dictionary)
/// - body: The body data to be sent with the function invocation. (Default: nil)
public init(method: Method? = nil, headers: [String: String] = [:], body: some Encodable) {
var headers = headers
var defaultHeaders = headers

switch body {
case let string as String:
headers["Content-Type"] = "text/plain"
defaultHeaders["Content-Type"] = "text/plain"
self.body = string.data(using: .utf8)
case let data as Data:
headers["Content-Type"] = "application/octet-stream"
defaultHeaders["Content-Type"] = "application/octet-stream"
self.body = data
default:
// default, assume this is JSON
headers["Content-Type"] = "application/json"
defaultHeaders["Content-Type"] = "application/json"
self.body = try? JSONEncoder().encode(body)
}

self.method = method
self.headers = headers
self.headers = defaultHeaders.merging(headers) { _, new in new }
}

/// Initializes the `FunctionInvokeOptions` structure.
Expand Down
17 changes: 14 additions & 3 deletions Tests/FunctionsTests/FunctionInvokeOptionsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,35 @@ import XCTest
@testable import Functions

final class FunctionInvokeOptionsTests: XCTestCase {
func testStringBody() {
func test_initWithStringBody() {
let options = FunctionInvokeOptions(body: "string value")
XCTAssertEqual(options.headers["Content-Type"], "text/plain")
XCTAssertNotNil(options.body)
}

func testDataBody() {
func test_initWithDataBody() {
let options = FunctionInvokeOptions(body: "binary value".data(using: .utf8)!)
XCTAssertEqual(options.headers["Content-Type"], "application/octet-stream")
XCTAssertNotNil(options.body)
}

func testEncodableBody() {
func test_initWithEncodableBody() {
struct Body: Encodable {
let value: String
}
let options = FunctionInvokeOptions(body: Body(value: "value"))
XCTAssertEqual(options.headers["Content-Type"], "application/json")
XCTAssertNotNil(options.body)
}

func test_initWithCustomContentType() {
let boundary = "Boundary-\(UUID().uuidString)"
let contentType = "multipart/form-data; boundary=\(boundary)"
let options = FunctionInvokeOptions(
headers: ["Content-Type": contentType],
body: "binary value".data(using: .utf8)!
)
XCTAssertEqual(options.headers["Content-Type"], contentType)
XCTAssertNotNil(options.body)
}
}

0 comments on commit e8ba6d1

Please sign in to comment.