首页 > 解决方案 > 尝试转换 EventLoopF​​uture 时出错输入

问题描述

我是一般编码的新手,尤其是期货的概念,所以耐心等待将不胜感激!以下函数的目标是检查 PostgreSQL 数据库中是否存在帐户。如果是,则返回一个空的 UUID;如果不存在帐户,则创建一个新帐户并返回其 UUID。当我尝试运行我的代码时,错误Cannot convert return expression of type 'EventLoopFuture<Account.idOut>' to return type 'Account.idOut'出现在.map { Account.idOut(id: account.id!) }. 我已经在这里环顾四周,似乎找不到任何解决此问题的方法。任何帮助将不胜感激,谢谢!!

func newAccount(req: Request) throws -> EventLoopFuture<Account.idOut> {
        let input = try req.content.decode(Account.postAccount.self)
        
        //check to see if account already exists
        return Account.query(on: req.db)
            .filter(\.$email == input.email)
            .first().map { checkAccount in
                if checkAccount == nil {
                    let id = UUID()
                    let account = Account(id: id, fullName: input.fullName, email: input.email, password: input.password, type: input.type)
                    return account.save(on: req.db)
                        .map { Account.idOut(id: account.id!) }
                } else {
                    return Account.idOut(id: UUID("00000000-0000-0000-0000-000000000000")!)
                }
            }
    }

标签: swiftevent-loopvapor

解决方案


总之,你需要返回相同的类型来满足编译器。if这肯定会与/ like yours有点混淆,else其中一个返回未来而一个不返回。解决它的方法是为两者返回一个未来,如下所示:

    func newAccount(req: Request) throws -> EventLoopFuture<Account.idOut> {
        let input = try req.content.decode(Account.postAccount.self)
        
        //check to see if account already exists
        return Account.query(on: req.db)
            .filter(\.$email == input.email)
            .first().flatMap { checkAccount in
                if checkAccount == nil {
                    let id = UUID()
                    let account = Account(id: id, fullName: input.fullName, email: input.email, password: input.password, type: input.type)
                    return account.create(on: req.db)
                        .map { Account.idOut(id: account.id!) }
                } else {
                    return req.eventLoop.future(Account.idOut(id: UUID("00000000-0000-0000-0000-000000000000")!))
                }
            }
    }

需要注意的重要事项:

  • 我把第一个改成mapa,flatMap因为你在里面返回一个未来
  • 当您提供 ID时,我使用create而不是保存操作,这会强制 Fluent 创建模型。save(Fluent 通常会为你设置 ID)
  • 我将帐户包裹在其中req.eventLoop.future-返回EventLoopFuture<Account.idOut>满足编译器的要求

推荐阅读