Caps-Server/Sources/App/routes.swift

49 lines
1.7 KiB
Swift
Raw Normal View History

import Vapor
2020-05-19 15:19:19 +02:00
/// Register your application's routes here.
///
/// [Learn More ](https://docs.vapor.codes/3.0/getting-started/structure/#routesswift)
2020-09-20 11:36:35 +02:00
func routes(_ app: Application) throws {
2020-05-19 15:19:19 +02:00
// Set the name of a cap
2020-09-20 11:36:35 +02:00
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")
2020-05-19 15:19:19 +02:00
throw CapError.invalidBody
}
2021-11-08 21:58:55 +01:00
try server.set(name: name, for: cap)
2020-05-19 15:19:19 +02:00
}
// Upload an image
2020-09-20 12:44:38 +02:00
app.postCatching("images", ":n") { request -> Data in
2020-09-20 11:36:35 +02:00
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")
2020-05-19 15:19:19 +02:00
throw CapError.invalidBody
}
2020-09-20 11:36:35 +02:00
let data = Data(buffer: buffer)
2021-11-08 21:58:55 +01:00
let newCount = try server.save(image: data, for: cap)
return "\(newCount)".data(using: .utf8)!
2020-05-19 15:19:19 +02:00
}
// Set a different version as the main image
2020-09-20 11:36:35 +02:00
app.getCatching("switch", ":n", ":v") { request in
2022-05-24 14:47:50 +02:00
guard let cap = request.parameters.get("n", as: Int.self), cap >= 0 else {
2020-09-20 11:36:35 +02:00
log("Invalid parameter for cap")
throw Abort(.badRequest)
}
2022-05-24 14:47:50 +02:00
guard let version = request.parameters.get("v", as: Int.self), version >= 0 else {
2020-09-20 11:36:35 +02:00
log("Invalid parameter for cap version")
throw Abort(.badRequest)
}
2021-11-08 21:58:55 +01:00
try server.switchMainImage(to: version, for: cap)
}
}