Files
vapor-po/Sources/App/Models/Vendor.swift

102 lines
1.9 KiB
Swift

import Fluent
import struct Foundation.UUID
import Vapor
// The primary database model.
final class Vendor: Model, @unchecked Sendable {
static let schema = "vendor"
@ID(key: .id)
var id: UUID?
@Field(key: "name")
var name: String
@Children(for: \.$vendor)
var branches: [VendorBranch]
init() {}
init(id: UUID? = nil, name: String) {
self.id = id
self.name = name
}
func toDTO(includeBranches: Bool? = nil) -> DTO {
.init(
id: id,
name: $name.value,
branches: ($branches.value != nil && $branches.value!.count > 0)
? $branches.value!.map { $0.toDTO() }
: (includeBranches == true) ? [] : nil
)
}
func applyUpdates(_ updates: Update) {
name = updates.name
}
}
// MARK: - Helpers.
extension Vendor {
struct Create: Content {
var name: String
func toModel() -> Vendor {
.init(name: name)
}
}
struct DTO: Content {
var id: UUID?
var name: String?
var branches: [VendorBranch.DTO]?
func toModel() -> Vendor {
let model = Vendor()
model.id = id
if let name {
model.name = name
}
return model
}
}
struct Migrate: AsyncMigration {
let name = "CreateVendor"
func prepare(on database: Database) async throws {
try await database.schema(Vendor.schema)
.id()
.field("name", .string, .required)
.unique(on: "name")
.create()
}
func revert(on database: Database) async throws {
try await database.schema(Vendor.schema).delete()
}
}
struct Update: Content {
var name: String
}
}
// MARK: - Validations
extension Vendor.Create: Validatable {
static func validations(_ validations: inout Validations) {
validations.add("name", as: String.self, is: !.empty)
}
}
extension Vendor.Update: Validatable {
static func validations(_ validations: inout Validations) {
validations.add("name", as: String.self, is: !.empty)
}
}