Skip to content

Commit

Permalink
duet/api: add some convenience methods
Browse files Browse the repository at this point in the history
  • Loading branch information
jaredh159 committed Nov 7, 2023
1 parent 651c374 commit 3e3d352
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
9 changes: 9 additions & 0 deletions api/Sources/Api/Models/Models+Duet.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,15 @@ extension Model {
try await Current.db.create(self)
}

@discardableResult
func upsert() async throws -> Self {
if (try? await Current.db.query(Self.self).byId(id).first()) != nil {
return try await create()
} else {
return try await save()
}
}

func delete() async throws {
try await Current.db.query(Self.self).byId(id).delete()
}
Expand Down
9 changes: 9 additions & 0 deletions duet/Sources/Duet/Relation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,15 @@ public enum OptionalChild<C: Duet.Identifiable> {
return loaded
}
}

public mutating func useLoaded(or load: () async throws -> C?) async throws -> C? {
guard case .loaded(let loaded) = self else {
let optionalChild = try await load()
self = .loaded(optionalChild)
return optionalChild
}
return loaded
}
}

public func connect<P: Duet.Identifiable, C: Duet.Identifiable>(
Expand Down

0 comments on commit 3e3d352

Please sign in to comment.