Update vapor

This commit is contained in:
Christoph Hagen 2020-09-20 11:36:35 +02:00
parent b52e4f5740
commit 5672fbf300
7 changed files with 79 additions and 75 deletions

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>

View File

@ -1,13 +1,23 @@
// swift-tools-version:5.0 // swift-tools-version:5.2
import PackageDescription import PackageDescription
let package = Package( let package = Package(
name: "CapCollectorServer", name: "CapCollectorServer",
platforms: [
.macOS(.v10_15)
],
dependencies: [ dependencies: [
.package(url: "https://github.com/vapor/vapor.git", .upToNextMinor(from: "3.3.0")), .package(url: "https://github.com/vapor/vapor.git", from: "4.0.0"),
], ],
targets: [ targets: [
.target(name: "App", dependencies: ["Vapor"]), .target(name: "App",
dependencies: [.product(name: "Vapor", package: "vapor")],
swiftSettings: [
// Enable better optimizations when building in Release configuration. Despite the use of
// the `.unsafeFlags` construct required by SwiftPM, this flag is recommended for Release
// builds. See <https://github.com/swift-server/guides#building-for-production> for details.
.unsafeFlags(["-cross-module-optimization"], .when(configuration: .release))
]),
.target(name: "Run", dependencies: ["App"]), .target(name: "Run", dependencies: ["App"]),
.testTarget(name: "AppTests", dependencies: ["App"]), .testTarget(name: "AppTests", dependencies: ["App"]),
] ]

View File

@ -7,37 +7,37 @@
import Vapor import Vapor
extension Router { extension Application {
func getCatching<T>(_ path: PathComponentsRepresentable..., call: @escaping (Request) throws -> T) { func getCatching<T>(_ path: PathComponent..., call: @escaping (Request) throws -> T) {
self.get(path) { (request: Request) -> HTTPResponse in self.get(path) { (request: Request) -> Response in
catching(path, request: request, closure: call) catching(path, request: request, closure: call)
} }
} }
func postCatching<T>(_ path: PathComponentsRepresentable..., call: @escaping (Request) throws -> T) { func postCatching<T>(_ path: PathComponent..., call: @escaping (Request) throws -> T) {
self.post(path) { (request: Request) -> HTTPResponse in self.post(path) { (request: Request) -> Response in
catching(path, request: request, closure: call) catching(path, request: request, closure: call)
} }
} }
} }
private func catching<T>(_ path: PathComponentsRepresentable..., request: Request, closure: @escaping (Request) throws -> T) -> HTTPResponse { private func catching<T>(_ path: [PathComponent], request: Request, closure: @escaping (Request) throws -> T) -> Response {
let route = path.convertToPathComponents().map { $0.string }.joined(separator: "/") let route = path.map { $0.string }.joined(separator: "/")
do { do {
let data = try closure(request) let data = try closure(request)
if let d = data as? Data { if let d = data as? Data {
return HTTPResponse(status: .ok, body: d) return Response(status: .ok, body: .init(data: d))
} else { } else {
return HTTPResponse(status: .ok) return Response(status: .ok)
} }
} catch let error as CapError { } catch let error as CapError {
log("\(route): Error \(error)") log("\(route): Error \(error)")
return HTTPResponse(status: error.response) return Response(status: error.response)
} catch { } catch {
log("\(route): Unhandled error: \(error)") log("\(route): Unhandled error: \(error)")
return HTTPResponse(status: .internalServerError) return Response(status: .internalServerError)
} }
} }

View File

@ -1,9 +0,0 @@
import Routing
import Vapor
/// Called after your application has initialized.
///
/// [Learn More ](https://docs.vapor.codes/3.0/getting-started/structure/#bootswift)
public func boot(_ app: Application) throws {
// your code here
}

View File

@ -1,17 +1,10 @@
import Vapor import Vapor
/// Called before your application initializes. // configures your application
/// public func configure(_ app: Application) throws {
/// [Learn More ](https://docs.vapor.codes/3.0/getting-started/structure/#configureswift) // uncomment to serve files from /Public folder
public func configure( // app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
_ config: inout Config,
_ env: inout Environment,
_ services: inout Services
) throws {
// Register routes to the router // Register routes to the router
let router = EngineRouter.default() try routes(app)
try routes(router)
services.register(router, as: Router.self)
// Configure the rest of your application here // Configure the rest of your application here
} }

View File

@ -1,4 +1,3 @@
import Routing
import Vapor import Vapor
// MARK: Paths // MARK: Paths
@ -56,14 +55,17 @@ private func count(of cap: Int) throws -> Int {
/// Register your application's routes here. /// Register your application's routes here.
/// ///
/// [Learn More ](https://docs.vapor.codes/3.0/getting-started/structure/#routesswift) /// [Learn More ](https://docs.vapor.codes/3.0/getting-started/structure/#routesswift)
public func routes(_ router: Router) throws { func routes(_ app: Application) throws {
try Log.set(logFile: logFile) try Log.set(logFile: logFile)
try loadCapNames() try loadCapNames()
// Get the name of a cap // Get the name of a cap
router.getCatching("name", Int.parameter) { request -> Data in app.getCatching("name", ":n") { request -> Data in
let cap = try request.parameters.next(Int.self) guard let cap = request.parameters.get("n", as: Int.self) else {
log("Invalid body data")
throw Abort(.badRequest)
}
let index = cap - 1 let index = cap - 1
guard index >= 0, index < caps.count else { guard index >= 0, index < caps.count else {
log("Trying to get name for invalid cap \(cap) (\(caps.count) caps loaded)") log("Trying to get name for invalid cap \(cap) (\(caps.count) caps loaded)")
@ -73,10 +75,14 @@ public func routes(_ router: Router) throws {
} }
// Set the name of a cap // Set the name of a cap
router.postCatching("name", Int.parameter) { request in app.postCatching("name", ":n") { request in
let cap = try request.parameters.next(Int.self) guard let cap = request.parameters.get("n", as: Int.self) else {
log("Invalid parameter for cap")
throw Abort(.badRequest)
}
let index = cap - 1 let index = cap - 1
guard let data = request.http.body.data, let name = String(data: data, encoding: .utf8) else { guard let buffer = request.body.data, let name = String(data: Data(buffer: buffer), encoding: .utf8) else {
log("Invalid body data")
throw CapError.invalidBody throw CapError.invalidBody
} }
guard index <= caps.count else { guard index <= caps.count else {
@ -101,11 +107,16 @@ public func routes(_ router: Router) throws {
} }
// Upload an image // Upload an image
router.postCatching("images", Int.parameter) { request -> Data in app.postCatching("images", "n") { request -> Data in
let cap = try request.parameters.next(Int.self) guard let cap = request.parameters.get("n", as: Int.self) else {
guard let data = request.http.body.data else { log("Invalid parameter for cap")
throw Abort(.badRequest)
}
guard let buffer = request.body.data else {
log("Invalid body data")
throw CapError.invalidBody throw CapError.invalidBody
} }
let data = Data(buffer: buffer)
let c = try count(of: cap) let c = try count(of: cap)
let f = file(of: cap, version: c) let f = file(of: cap, version: c)
guard !fm.fileExists(atPath: f.path) else { guard !fm.fileExists(atPath: f.path) else {
@ -117,21 +128,30 @@ public func routes(_ router: Router) throws {
} }
// Get count of a cap // Get count of a cap
router.getCatching("count", Int.parameter) { request -> Data in app.getCatching("count", ":c") { request -> Data in
let cap = try request.parameters.next(Int.self) guard let cap = request.parameters.get("c", as: Int.self) else {
log("Invalid parameter for cap")
throw Abort(.badRequest)
}
let c = try count(of: cap) let c = try count(of: cap)
return "\(c)".data(using: .utf8)! return "\(c)".data(using: .utf8)!
} }
// Get the count of all caps // Get the count of all caps
router.getCatching("counts") { request -> Data in app.getCatching("counts") { request -> Data in
try (1...caps.count).map { UInt8(try count(of: $0)) }.convertToData() Data(try (1...caps.count).map({ UInt8(try count(of: $0)) }))
} }
// Set a different version as the main image // Set a different version as the main image
router.getCatching("switch", Int.parameter, Int.parameter) { request in app.getCatching("switch", ":n", ":v") { request in
let cap = try request.parameters.next(Int.self) guard let cap = request.parameters.get("n", as: Int.self) else {
let version = try request.parameters.next(Int.self) log("Invalid parameter for cap")
throw Abort(.badRequest)
}
guard let version = request.parameters.get("v", as: Int.self) else {
log("Invalid parameter for cap version")
throw Abort(.badRequest)
}
guard version > 0 else { guard version > 0 else {
log("Not switching cap \(cap) to image \(version)") log("Not switching cap \(cap) to image \(version)")
return return

View File

@ -1,26 +1,9 @@
import App import App
import Service
import Vapor import Vapor
import Foundation
// The contents of main are wrapped in a do/catch block because any errors that get raised to the top level will crash Xcode var env = try Environment.detect()
do { try LoggingSystem.bootstrap(from: &env)
var config = Config.default() let app = Application(env)
var env = try Environment.detect() defer { app.shutdown() }
var services = Services.default() try configure(app)
try app.run()
try App.configure(&config, &env, &services)
let app = try Application(
config: config,
environment: env,
services: services
)
try App.boot(app)
try app.run()
} catch {
print(error)
exit(1)
}