Caps-Server/Sources/App/routes.swift
2022-06-11 00:20:43 +02:00

43 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 {
guard let key = request.headers.first(name: "key") else {
throw Abort(.badRequest)
}
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)
}
}