Caps-Server/Sources/App/routes.swift

73 lines
2.5 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
// Get the name of a cap
2020-09-20 11:36:35 +02:00
app.getCatching("name", ":n") { request -> Data in
guard let cap = request.parameters.get("n", as: Int.self) else {
log("Invalid body data")
throw Abort(.badRequest)
}
2021-11-08 21:58:55 +01:00
return try server.name(for: cap)
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
}
// Get count of a cap
2020-09-20 11:36:35 +02:00
app.getCatching("count", ":c") { request -> Data in
guard let cap = request.parameters.get("c", as: Int.self) else {
log("Invalid parameter for cap")
throw Abort(.badRequest)
}
2021-11-08 21:58:55 +01:00
let c = try server.count(of: cap)
2020-05-19 15:19:19 +02:00
return "\(c)".data(using: .utf8)!
}
// Get the count of all caps
2020-09-20 11:36:35 +02:00
app.getCatching("counts") { request -> Data in
2021-11-08 21:58:55 +01:00
try server.getCountData()
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
guard let cap = request.parameters.get("n", as: Int.self) else {
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)
}
2021-11-08 21:58:55 +01:00
try server.switchMainImage(to: version, for: cap)
}
}