等待异步任务在Vapor中完成请求

时间:2019-06-26 04:17:51

标签: swift fluent vapor server-side-swift vapor-fluent

我正在使用服务器端swift框架Vapor编写API。我的模型很简单。我有一个Workout表,该表与Circuit表有很多关系,该表与Exercise表有很多关系。当api使用者创建锻炼时,json包含锻炼中的所有电路和锻炼。这是一个示例:

{
    ...
    circuits: [{
        ...,
        exercises: [{
            "title": ...
        }, {
            "title": ...
        }]
    }, {
        ...,
        exercises: [{
            "title": ...
        }, {
            "title": ...
        }]
    }]
}

我遇到的问题是当用户在多个回路中进行相同的练习时,正在创建重复的练习。我在创建新练习之前查询数据库,但似乎所有保存操作都是异步进行的,这使我无法在保存新练习之前在数据库中检测到具有相同ID /标题的现有练习。这是我的代码:

private func saveExercise(on conn: DatabaseConnectable, with content: WorkoutCreateExerciseContent, for authUser: User) throws -> Future<Exercise> {

        if let exerciseId: UUID = content.id {

            return Exercise.find(exerciseId, on: conn)
                .unwrap(or: Abort(.badRequest, reason: "No exercise for id: \(exerciseId.uuidString)"))

        } else if let title: String = content.title, let isPublicallyVisible: Bool = content.isPublicallyVisible {

            return Exercise.query(on: conn).filter(\.title == title).filter(\.directions == content.directions).first().flatMap({ (possibleMatchingExercise: Exercise?) -> Future<Exercise> in

                if let matchingExercise: Exercise = possibleMatchingExercise {

                    return conn.future(matchingExercise)

                } else {
                    print("xxx Found no match for \(title)")
                    let newExercise: Exercise = Exercise(
                        title: title,
                        directions: content.directions,
                        isPublicallyVisible: isPublicallyVisible
                    )
                    newExercise.userId = authUser.id
                    return newExercise.save(on: conn)

                }

            })

        } else {

            throw Abort(.badRequest, reason: """
                Bad data for exercise. Expecting either of the following:
                {
                    /"id/": /"some id/"
                }
                or
                {
                    /"title/": /"some title/"
                    /"directions/": /"(optional)/",
                    /"isPublicallyVisible/": false
                }
                id takes priority over other properties.
            """)
        }

    }

    private func saveCircuit(on conn: DatabaseConnectable, with content: CircuitCreateContent, order: Int, workoutId: UUID, authUser: User) throws -> Future<Circuit> {

        return try content.exercises.map({ (exerciseContent: WorkoutCreateExerciseContent) throws -> Future<Exercise> in

            let createdExercise: Future<Exercise> = try self.saveExercise(
                on: conn,
                with: exerciseContent,
                for: authUser
            )

            return createdExercise

        })
        .flatten(on: conn)
        .flatMap({ (exercises: [Exercise]) -> Future<Circuit> in

            let circuit: Circuit = Circuit(
                workoutId: workoutId,
                order: order,
                exerciseDuration: content.exerciseDuration,
                restDuration: content.restDuration,
                exerciseIDs: exercises.compactMap({ $0.id })
            )

            return circuit.save(on: conn)

        })

    }

    func saveWorkout(_ conn: DatabaseConnectable,  _ authentiatedUser: User, _ content: WorkoutCreateContent) throws -> Future<Workout> {

        let workout: Workout = content.makeWorkout()

        workout.userId = authentiatedUser.id

        // First save the exercises

        let createdWorkout: Future<Workout> = workout.save(on: conn).flatMap({ (savedWorkout: Workout) -> Future<Workout> in

            let createdCircuits: Future<[Circuit]> = try content.circuits.enumerated().map({ (order: Int, circuitContent: CircuitCreateContent) throws -> Future<Circuit> in

                let createdCircuit: Future<Circuit> = try self.saveCircuit(
                    on: conn, with: circuitContent,
                    order: order,
                    workoutId: savedWorkout.id!,
                    authUser: authentiatedUser
                )

                return createdCircuit

            })
            .flatten(on: conn)

            return createdCircuits.then({ _ -> Future<Workout> in
                return conn.future(savedWorkout)
            })

        })

        return createdWorkout

    }

有人看到我在这里想念的东西吗?有没有办法在开始新的Future之前等待Future完成?我是Vapor的新手,所以我对Vapor的流利api不太熟悉。

1 个答案:

答案 0 :(得分:2)

假设我们有两种假想方法返回Future<>

func randomUInt() -> Future<UInt> { ... }
func multiply(value: UInt, by multiplier: UInt) -> Future<UInt> { ... }

,我们想将随机数乘以5,但是如果随机数为零或1,则要抛出错误。因此,我们需要等待随机数后才能调用multiply(value: ,by: )方法。

let result: Future<UInt> = randomUInt().flatMap { (value) -> Future<UInt> in
    guard value > 1 else { throw YourError }
    return multiply(value: value, by: 5)
}