feat: Adds createMany for rooms, in prep for parsing / uploading a csv file of room loads.
All checks were successful
CI / Linux Tests (push) Successful in 7m0s
All checks were successful
CI / Linux Tests (push) Successful in 7m0s
This commit is contained in:
@@ -90,6 +90,7 @@ public struct DatabaseClient: Sendable {
|
||||
@DependencyClient
|
||||
public struct Rooms: Sendable {
|
||||
public var create: @Sendable (Room.Create) async throws -> Room
|
||||
public var createMany: @Sendable ([Room.Create]) async throws -> [Room]
|
||||
public var delete: @Sendable (Room.ID) async throws -> Void
|
||||
public var deleteRectangularSize:
|
||||
@Sendable (Room.ID, Room.RectangularSize.ID) async throws -> Room
|
||||
|
||||
@@ -15,6 +15,13 @@ extension DatabaseClient.Rooms: TestDependencyKey {
|
||||
try await model.validateAndSave(on: database)
|
||||
return try model.toDTO()
|
||||
},
|
||||
createMany: { rooms in
|
||||
try await rooms.asyncMap { request in
|
||||
let model = try request.toModel()
|
||||
try await model.validateAndSave(on: database)
|
||||
return try model.toDTO()
|
||||
}
|
||||
},
|
||||
delete: { id in
|
||||
guard let model = try await RoomModel.find(id, on: database) else {
|
||||
throw NotFoundError()
|
||||
|
||||
41
Sources/DatabaseClient/Internal/Sequence+asyncMap.swift
Normal file
41
Sources/DatabaseClient/Internal/Sequence+asyncMap.swift
Normal file
@@ -0,0 +1,41 @@
|
||||
import Foundation
|
||||
|
||||
extension Sequence {
|
||||
|
||||
// Taken from: https://forums.swift.org/t/are-there-any-kind-of-asyncmap-method-for-a-normal-sequence/77354/7
|
||||
func asyncMap<Result: Sendable>(
|
||||
_ transform: @escaping @Sendable (Element) async throws -> Result
|
||||
) async rethrows -> [Result] where Element: Sendable {
|
||||
try await withThrowingTaskGroup(of: (Int, Result).self) { group in
|
||||
|
||||
var i = 0
|
||||
var iterator = self.makeIterator()
|
||||
var results = [Result?]()
|
||||
results.reserveCapacity(underestimatedCount)
|
||||
|
||||
func submitTask() throws {
|
||||
try Task.checkCancellation()
|
||||
if let element = iterator.next() {
|
||||
results.append(nil)
|
||||
group.addTask { [i] in try await (i, transform(element)) }
|
||||
i += 1
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Add initial tasks
|
||||
for _ in 0..<ProcessInfo.processInfo.processorCount {
|
||||
try submitTask()
|
||||
}
|
||||
|
||||
// Submit more tasks as results complete
|
||||
while let (index, result) = try await group.next() {
|
||||
results[index] = result
|
||||
try submitTask()
|
||||
}
|
||||
|
||||
return results.compactMap { $0 }
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user