-
Notifications
You must be signed in to change notification settings - Fork 53
Open
Description
JSON responses are common for a web server. With this extension (serializing dates as millis by default to ease JS clients):
extension HTTPResponse {
static let jsonTimestampMillisEncoder: JSONEncoder = {
let jsonEncoder = JSONEncoder()
jsonEncoder.dateEncodingStrategy = .millisecondsSince1970
return jsonEncoder
}()
static func json(_ encodable: Encodable, jsonEncoder: JSONEncoder = jsonTimestampMillisEncoder) throws -> HTTPResponse {
HTTPResponse(statusCode: .ok, body: try jsonEncoder.encode(encodable))
}
}
one can easily return a JSON ready to be consumed by another application:
struct Cat: Codable {
let birthDate: Date
let name: String
}
struct MyHandler : HTTPHandler {
func handleRequest(_ request: HTTPRequest) async throws -> HTTPResponse {
try .json(Cat(birthDate: Date(), name: "Loris"))
}
}
If you think it's a valuable addition, feel free to add it in the library 🍻
Metadata
Metadata
Assignees
Labels
No labels