Caps-Server/Sources/App/Router+Extensions.swift

50 lines
1.4 KiB
Swift
Raw Normal View History

2020-05-19 15:19:19 +02:00
import Vapor
2020-09-20 11:36:35 +02:00
extension Application {
2020-05-19 15:19:19 +02:00
2020-09-20 11:36:35 +02:00
func getCatching<T>(_ path: PathComponent..., call: @escaping (Request) throws -> T) {
self.get(path) { (request: Request) -> Response in
2020-05-19 15:19:19 +02:00
catching(path, request: request, closure: call)
}
}
2020-09-20 11:36:35 +02:00
func postCatching<T>(_ path: PathComponent..., call: @escaping (Request) throws -> T) {
self.post(path) { (request: Request) -> Response in
2020-05-19 15:19:19 +02:00
catching(path, request: request, closure: call)
}
}
}
2020-09-20 11:36:35 +02:00
private func catching<T>(_ path: [PathComponent], request: Request, closure: @escaping (Request) throws -> T) -> Response {
2020-05-19 15:19:19 +02:00
2020-09-20 11:36:35 +02:00
let route = path.map { $0.string }.joined(separator: "/")
2020-05-19 15:19:19 +02:00
do {
let data = try closure(request)
if let d = data as? Data {
2020-09-20 11:36:35 +02:00
return Response(status: .ok, body: .init(data: d))
2020-05-19 15:19:19 +02:00
} else {
2020-09-20 11:36:35 +02:00
return Response(status: .ok)
2020-05-19 15:19:19 +02:00
}
} catch let error as CapError {
log("\(route): Error \(error)")
2020-09-20 11:36:35 +02:00
return Response(status: error.response)
2020-05-19 15:19:19 +02:00
} catch {
2020-05-25 10:05:16 +02:00
log("\(route): Unhandled error: \(error)")
2020-09-20 11:36:35 +02:00
return Response(status: .internalServerError)
2020-05-19 15:19:19 +02:00
}
}
extension PathComponent {
var string: String {
switch self {
case .constant(let value):
return value
case .parameter(let value):
return "<\(value)>"
default:
return "\(self)"
}
}
}