Caps-Server/Sources/App/Router+Extensions.swift
2020-05-25 10:05:16 +02:00

57 lines
1.6 KiB
Swift

//
// Router+Extensions.swift
// App
//
// Created by Christoph on 05.05.20.
//
import Vapor
extension Router {
func getCatching<T>(_ path: PathComponentsRepresentable..., call: @escaping (Request) throws -> T) {
self.get(path) { (request: Request) -> HTTPResponse in
catching(path, request: request, closure: call)
}
}
func postCatching<T>(_ path: PathComponentsRepresentable..., call: @escaping (Request) throws -> T) {
self.post(path) { (request: Request) -> HTTPResponse in
catching(path, request: request, closure: call)
}
}
}
private func catching<T>(_ path: PathComponentsRepresentable..., request: Request, closure: @escaping (Request) throws -> T) -> HTTPResponse {
let route = path.convertToPathComponents().map { $0.string }.joined(separator: "/")
do {
let data = try closure(request)
if let d = data as? Data {
return HTTPResponse(status: .ok, body: d)
} else {
return HTTPResponse(status: .ok)
}
} catch let error as CapError {
log("\(route): Error \(error)")
return HTTPResponse(status: error.response)
} catch {
log("\(route): Unhandled error: \(error)")
return HTTPResponse(status: .internalServerError)
}
}
extension PathComponent {
var string: String {
switch self {
case .constant(let value):
return value
case .parameter(let value):
return "<\(value)>"
default:
return "\(self)"
}
}
}