Skip to content

Commit

Permalink
add additionalHeaders to initializer + docc and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
lovetodream committed Sep 3, 2024
1 parent b94300e commit 178d4c4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
18 changes: 17 additions & 1 deletion Sources/HummingbirdElementary/HTMLResponse.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,31 @@ public struct HTMLResponse<Content: HTML & Sendable>: Sendable {
public var chunkSize: Int

/// Response headers
///
/// It can be used to add additional headers to a predefined set of fields.
///
/// - Note: If a new set of headers is assigned, all predefined headers are removed.
///
/// ```swift
/// var response = HTMLResponse { ... }
/// response.headers[.init("foo")!] = "bar"
/// return response
/// ```
public var headers: HTTPFields = [.contentType: "text/html; charset=utf-8"]

/// Creates a new HTMLResponse
///
/// - Parameters:
/// - chunkSize: The number of bytes to write to the response body at a time.
/// - additionalHeaders: Additional headers to be merged with predefined headers.
/// - content: The `HTML` content to render in the response.
public init(chunkSize: Int = 1024, @HTMLBuilder content: () -> Content) {
public init(chunkSize: Int = 1024, additionalHeaders: HTTPFields = [:], @HTMLBuilder content: () -> Content) {
self.chunkSize = chunkSize
if additionalHeaders.contains(.contentType) {
self.headers = additionalHeaders
} else {
self.headers = [.contentType: "text/html; charset=utf-8"] + additionalHeaders
}
self.content = content()
}
}
Expand Down
16 changes: 15 additions & 1 deletion Tests/HummingbirdElementaryTests/HTMLResponseTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,29 @@ final class HTMLResponseTests: XCTestCase {

func testRespondsWithCustomHeaders() async throws {
let router = Router().get { _, _ in
var response = HTMLResponse { TestPage() }
var response = HTMLResponse(additionalHeaders: [.init("foo")!: "bar"]) { EmptyHTML() }
response.headers[.init("hx-refresh")!] = "true"
return response
}

try await Application(router: router).test(.router) { client in
let response = try await client.execute(uri: "/", method: .get)

XCTAssertEqual(response.headers[.init("foo")!], "bar")
XCTAssertEqual(response.headers[.init("hx-refresh")!], "true")
XCTAssertEqual(response.headers[.contentType], "text/html; charset=utf-8")
}
}

func testRespondsWithOverwrittenContentType() async throws {
let router = Router().get { _, _ in
HTMLResponse(additionalHeaders: [.contentType: "new"]) { EmptyHTML() }
}

try await Application(router: router).test(.router) { client in
let response = try await client.execute(uri: "/", method: .get)

XCTAssertEqual(response.headers[.contentType], "new")
}
}
}
Expand Down

0 comments on commit 178d4c4

Please sign in to comment.