Caps-Server/Sources/App/routes.swift
2022-05-28 21:59:32 +02:00

41 lines
1.2 KiB
Swift
Executable File

import Vapor
/// The decoder to extract caps from JSON payloads given to the `cap` route.
private let decoder = JSONDecoder()
private func authorize(_ request: Request) throws {
let key = try request.query.get(String.self, at: "key")
guard server.hasAuthorization(for: key) else {
throw Abort(.forbidden)
}
}
func routes(_ app: Application) throws {
// Add or change a cap
app.postCatching("cap") { request in
try authorize(request)
guard let buffer = request.body.data else {
log("Invalid body data")
throw CapError.invalidBody
}
let cap = try decoder.decode(Cap.self, from: buffer)
try server.addOrUpdate(cap)
}
// Upload an image
app.postCatching("images", ":n") { request in
try authorize(request)
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)
try server.save(image: data, for: cap)
}
}