Caps-Server/Sources/App/routes.swift
2022-05-24 14:47:50 +02:00

49 lines
1.7 KiB
Swift
Executable File

import Vapor
/// Register your application's routes here.
///
/// [Learn More ](https://docs.vapor.codes/3.0/getting-started/structure/#routesswift)
func routes(_ app: Application) throws {
// Set the name of a cap
app.postCatching("name", ":n") { request in
guard let cap = request.parameters.get("n", as: Int.self) else {
log("Invalid parameter for cap")
throw Abort(.badRequest)
}
guard let buffer = request.body.data, let name = String(data: Data(buffer: buffer), encoding: .utf8) else {
log("Invalid body data")
throw CapError.invalidBody
}
try server.set(name: name, for: cap)
}
// Upload an image
app.postCatching("images", ":n") { request -> Data in
guard let cap = request.parameters.get("n", as: Int.self) else {
log("Invalid parameter for cap")
throw Abort(.badRequest)
}
guard let buffer = request.body.data else {
log("Invalid body data")
throw CapError.invalidBody
}
let data = Data(buffer: buffer)
let newCount = try server.save(image: data, for: cap)
return "\(newCount)".data(using: .utf8)!
}
// Set a different version as the main image
app.getCatching("switch", ":n", ":v") { request in
guard let cap = request.parameters.get("n", as: Int.self), cap >= 0 else {
log("Invalid parameter for cap")
throw Abort(.badRequest)
}
guard let version = request.parameters.get("v", as: Int.self), version >= 0 else {
log("Invalid parameter for cap version")
throw Abort(.badRequest)
}
try server.switchMainImage(to: version, for: cap)
}
}