混淆地图与平面地图:无法使用类型为 '(() -> EventLoopFuture)' 的参数列表调用'flatMap'



我是 Swift 初学者,在 Vapor 框架中工作,开发一个注册过程,需要几个系列步骤才能工作。我在以下代码中遇到问题,Xcode 表示标记的行上存在错误:

func signup(_ req: Request) throws -> Future<RecordA> {
return try req.content.decode(RecordACreation.self).flatMap(to: RecordACreation.self) { recordACreation in
// Prevent a recordA email from being used twice.
RecordA(on: req).filter(.email == recordACreation).first().map(to: RecordA.self) { optionalExistingRecordAByEmail in
if let _ = optionalExistingRecordAByEmail {
throw Abort(.unprocessableEntity, reason: "RecordA email already exists")
}
}.flatMap { // Xcode indicates there's an error here.
// Prevent an recordB email from being used twice.
return RecordB.query(on: req).filter(.email == recordACreation.recordBEmail).first().map(to: RecordA.self) { optionalExistingRecordBByEmail in
if let _ = optionalExistingRecordBByEmail {
throw Abort(.unprocessableEntity, reason: "RecordB email already exists.")
}
}
}.flatMap {
// If the recordB's password could not be successfully hashed.
guard let recordBPassword = try? BCrypt.hash(recordACreation.recordBPassword) else {
throw Abort(.unprocessableEntity, reason: "Password was unhashed")
}
// Ensure a verification token is generated successfully.
guard let optionalVerificationToken = try? VerificationTokenService.generate(), let verificationToken = optionalVerificationToken else {
throw Abort(.unprocessableEntity, reason: "Verification token could not be generated.")
}
let recordA = RecordA(name: recordACreation.recordAName, email: recordACreation.recordAEmail)
return req.transaction(on: .sqlite) { conn in
// TODO: Send email on signup success.
return recordA.save(on: conn).map(to: RecordA.self) { savedRecordA in
guard let recordAId = recordA.id else {
throw Abort(.unprocessableEntity, reason: "Verification token could not be generated.")
}
_ = RecordB(name: recordACreation.recordBName, email: recordACreation.recordBEmail, password: recordBPassword, recordAId: recordAId, verificationToken: verificationToken).save(on: conn)
return savedRecordA
}
}
}
}
}

错误如下:

无法使用类型为"(() -> EventLoopFuture)"的参数列表调用"flatMap">

我不完全了解适当选择mapflatMap之间的机制,因此这可能是这里问题的原因。思潮?

问题是RecordA查询后的map调用:

RecordA(on: req).filter(.email == recordACreation).first().map(to: RecordA.self) { optionalExistingRecordAByEmail in
if let _ = optionalExistingRecordAByEmail {
throw Abort(.unprocessableEntity, reason: "RecordA email already exists")
}
}

您正在将RecordA.self传递给to参数,该参数将闭包的返回类型设置为RecordA。相反,您不会返回任何东西。您应该删除to参数,它应该可以工作:

RecordA(on: req).filter(.email == recordACreation).first().map { optionalExistingRecordAByEmail in
if let _ = optionalExistingRecordAByEmail {
throw Abort(.unprocessableEntity, reason: "RecordA email already exists")
}
}

最新更新