Files
vapor-po/Sources/App/Extensions/Request+extensions.swift

44 lines
1.2 KiB
Swift

import Elementary
import Vapor
import VaporElementary
extension Request {
func ensureValidContent<T>(_ decoding: T.Type) throws -> T where T: Content, T: Validatable {
try T.validate(content: self)
return try content.decode(T.self)
}
func ensureIDPathComponent<T: LosslessStringConvertible>(
as decoding: T.Type = UUID.self,
key: String = "id"
) throws -> T {
guard let id = parameters.get(key, as: T.self) else {
throw Abort(.badRequest, reason: "Id not supplied.")
}
return id
}
var isHtmxRequest: Bool {
headers.contains(name: "hx-request")
}
func render<C: HTML>(
@HTMLBuilder html: () async throws -> C
) async rethrows -> HTMLResponse where C: Sendable {
let html = try await html()
return HTMLResponse { html }
}
// Render the html if we're an htmx request, otherwise render the main page.
func render<C: HTML, D: SendableHTMLDocument>(
mainPage: (C) async throws -> D,
@HTMLBuilder html: () async throws -> C
) async rethrows -> HTMLResponse where C: Sendable {
let html = try await html()
guard isHtmxRequest else {
return try await render { try await mainPage(html) }
}
return HTMLResponse { html }
}
}