Last active
December 19, 2017 04:57
-
-
Save kjessup/34ae066dc834bf658e93cebbf487fd6c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Route { | |
init<IN: Codable, OUT: Codable>(uri: String, _ handler: @escaping (IN) throws -> OUT) { | |
self.init(method: .post, uri: uri) { | |
req, resp in | |
do { | |
guard let body = req.postBodyBytes else { | |
throw DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "This request requires JSON input.")) | |
} | |
let input = try JSONDecoder().decode(IN.self, from: Data(bytes: body)) | |
resp.setBody(bytes: try JSONEncoder().encode(try handler(input)).map{$0}) | |
.setHeader(.contentType, value: MimeType(type: .application, subType: "json").longType) | |
.completed(status: .ok) | |
} catch { | |
resp.setBody(string: "\(error.localizedDescription)") | |
.completed(status: .internalServerError) | |
} | |
} | |
} | |
init<OUT: Codable>(uri: String, _ handler: @escaping () throws -> OUT) { | |
self.init(method: .get, uri: uri) { | |
req, resp in | |
do { | |
resp.setBody(bytes: try JSONEncoder().encode(try handler()).map{$0}) | |
.setHeader(.contentType, value: MimeType(type: .application, subType: "json").longType) | |
.completed(status: .ok) | |
} catch { | |
resp.setBody(string: "\(error.localizedDescription)") | |
.completed(status: .internalServerError) | |
} | |
} | |
} | |
} | |
// usage | |
struct HealthCheckResponse: Codable { | |
let status: String | |
} | |
let healthCheck = Route(uri: "/healthcheck") { | |
() -> HealthCheckResponse in | |
return HealthCheckResponse(status: "OK") | |
} | |
// add healthCheck to your Routes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment