Vapor 4/Fluent,具有嵌套数据库查找功能 return return EventLoopF​​uture<bool>

Vapor 4/Fluent, function with nested database lookup to return return EventLoopFuture<bool>

我正在尝试编写一个接受我的 UserModel 的函数,并执行一些检查以查看用户是否

  1. 已锁定
  2. 在一段时间内尝试登录的次数不多。

然后 return 是结果的布尔指示。

查找在我的身份验证过程中进行。但我想分解确定是否允许用户(尝试)登录的代码,这样我就可以在多个地方使用它而无需重复代码。

但是(Vapor/Swift 的新手)我遇到了一个错误,我无法弄清楚我做错了什么: 无法将 'EventLoopFuture' 类型的 return 表达式转换为 return 类型 'Bool'

错误在 }.all().map { 行(单独分隔成一行,因此更容易找到)。

明智的数据库结构我有 2 个表:

到目前为止,这是我的代码片段:

func CanUserLogin(user: UserModel, req: Request) -> EventLoopFuture<Bool> {
  if(!(user.locked ?? false)) {
    let userProfileId = user.userprofile

    return Usertype.query(on: req.db)
      .filter(\.$profilenum == userProfileId)
      .first().map { useraccess in
        let badloginperiod = Double((useraccess!.badloginperiod ?? 0) * -1 * 60) // convert minutes to seconds (we need a negative number)
        let lookUpDate = Date().addingTimeInterval(badloginperiod)

        return Userlog.query(on: req.db).group(.and) {
          and in
          and.filter(\.$username == user.username)
          and.filter(\.$datecreated >= lookUpDate)
        }.all().map {
          UserLogs -> Bool in
          let value = userLogs.count

          // the account is locked or the max attempts for the time peroid
          if(value >= (useraccess.maxloginattempts ?? 3)) {
            return false
          } else {
            return true
          }
        }
    }
  }
}

任何方向将不胜感激。

您尝试从 map 块中 return EventLoopFuture,但您只能从中 return non-future 值。因此,您必须在 Usertype 查询上使用 flatMap 而不是 map

检查此代码

func canUserLogin(user: UserModel, req: Request) -> EventLoopFuture<Bool> {
    guard user.locked != true else {
        return req.eventLoop.makeFailedFuture(Abort(.badRequest, reason: "User is locked"))
    }
    let userProfileId = user.userprofile
    return Usertype.query(on: req.db)
        .filter(\.$profilenum == userProfileId)
        .first()
        .unwrap(or: Abort(.forbidden, reason: "No access"))
        .flatMap { userAccess in
            let badloginperiod = Double((useraccess.badloginperiod ?? 0) * -1 * 60) // convert minutes to seconds (we need a negative number)
            let lookUpDate = Date().addingTimeInterval(badloginperiod)
            return Userlog.query(on: req.db).group(.and) {
              [=10=].filter(\.$username == user.username)
              [=10=].filter(\.$datecreated >= lookUpDate)
            }.all().map { attempts -> Bool in
                // the account is locked or the max attempts for the time peroid
                if attempts.count >= (userAccess.maxloginattempts ?? 3) {
                    return false
                } else {
                    return true
                }
            }
    }
}