import Fluent import Vapor struct VendorBranchDB { func create( _ model: VendorBranch.Create, for vendorID: Vendor.IDValue, on db: any Database ) async throws -> VendorBranch.DTO { let branch = model.toModel() guard let vendor = try await Vendor.find(vendorID, on: db) else { throw Abort(.badRequest, reason: "Vendor does not exist.") } try await vendor.$branches.create(branch, on: db) return branch.toDTO() } func fetchAll(withVendor: Bool? = nil, on db: any Database) async throws -> [VendorBranch.DTO] { var query = VendorBranch.query(on: db) if withVendor == true { query = query.with(\.$vendor) } return try await query.all().map { $0.toDTO() } } func fetch(for vendorID: Vendor.IDValue, on db: any Database) async throws -> [VendorBranch.DTO] { guard let vendor = try await Vendor.query(on: db) .filter(\.$id == vendorID) .with(\.$branches) .first() else { throw Abort(.notFound) } return vendor.branches.map { $0.toDTO() } } func get(id: VendorBranch.IDValue, on db: any Database) async throws -> VendorBranch.DTO? { try await VendorBranch.find(id, on: db).map { $0.toDTO() } } func update( id: VendorBranch.IDValue, with updates: VendorBranch.Update, on db: any Database ) async throws -> VendorBranch.DTO { guard let branch = try await VendorBranch.find(id, on: db) else { throw Abort(.notFound) } branch.applyUpdates(updates) try await branch.save(on: db) return branch.toDTO() } func delete(id: VendorBranch.IDValue, on db: any Database) async throws { guard let branch = try await VendorBranch.find(id, on: db) else { throw Abort(.notFound) } try await branch.delete(on: db) } }