import DatabaseClient import Dependencies import Fluent import SharedModels import Vapor struct VendorBranchApiController: RouteCollection { @Dependency(\.database.vendorBranches) var vendorBranches func boot(routes: any RoutesBuilder) throws { let prefix = routes.apiProtected(route: "vendors") let root = prefix.grouped("branches") root.get(use: index(req:)) root.group(":id") { $0.put(use: update(req:)) $0.delete(use: delete(req:)) } prefix.group(":vendorID", "branches") { $0.get(use: indexForVendor(req:)) $0.post(use: create(req:)) } } @Sendable func index(req: Request) async throws -> [VendorBranch] { try await vendorBranches.fetchAll() } @Sendable func indexForVendor(req: Request) async throws -> [VendorBranch] { guard let id = req.parameters.get("vendorID", as: Vendor.ID.self) else { throw Abort(.badRequest, reason: "Vendor id not provided.") } return try await vendorBranches.fetchAll(.for(vendorID: id)) } @Sendable func create(req: Request) async throws -> VendorBranch { let id = try req.ensureIDPathComponent(key: "vendorID") let content = try req.content.decode(BranchCreateRequest.self) return try await vendorBranches.create( .init(name: content.name, vendorID: id) ) } @Sendable func update(req: Request) async throws -> VendorBranch { return try await vendorBranches.update( req.ensureIDPathComponent(), req.content.decode(VendorBranch.Update.self) ) } @Sendable func delete(req: Request) async throws -> HTTPStatus { try await vendorBranches.delete(req.ensureIDPathComponent()) return .ok } } private struct BranchCreateRequest: Content { let name: String }