import Dependencies import Fluent import Vapor struct VendorBranchApiController: RouteCollection { @Dependency(\.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.DTO] { try await vendorBranches.fetchAll() } @Sendable func indexForVendor(req: Request) async throws -> [VendorBranch.DTO] { guard let id = req.parameters.get("vendorID", as: Vendor.IDValue.self) else { throw Abort(.badRequest, reason: "Vendor id not provided.") } return try await vendorBranches.fetchForVendor(id) } @Sendable func create(req: Request) async throws -> VendorBranch.DTO { guard let id = req.parameters.get("vendorID", as: Vendor.IDValue.self) else { throw Abort(.badRequest, reason: "Vendor id not provided.") } try VendorBranch.Create.validate(content: req) let model = try req.content.decode(VendorBranch.Create.self) return try await vendorBranches.create(model, id) } @Sendable func update(req: Request) async throws -> VendorBranch.DTO { guard let id = req.parameters.get("id", as: VendorBranch.IDValue.self) else { throw Abort(.badRequest, reason: "Vendor branch id not provided.") } try VendorBranch.Update.validate(content: req) let updates = try req.content.decode(VendorBranch.Update.self) return try await vendorBranches.update(id, updates) } @Sendable func delete(req: Request) async throws -> HTTPStatus { guard let id = req.parameters.get("id", as: VendorBranch.IDValue.self) else { throw Abort(.badRequest, reason: "Vendor branch id not provided.") } try await vendorBranches.delete(id) return .ok } }