【问题标题】:Accessing database in a command在命令中访问数据库
【发布时间】:2018-05-07 07:12:42
【问题描述】:

我想创建一个命令,您可以在其中创建用户(如数据库种子)。

但是,我无法在命令中访问数据库,我的代码如下:

import Command
import Crypto

struct CreateUserCommand: Command {
    var arguments: [CommandArgument] {
        return [.argument(name: "email")]
    }

    var options: [CommandOption] {
        return [
            .value(name: "password", short: "p", default: "", help: ["Password of a user"]),
        ]
    }

    var help: [String] {
        return ["Create a user with provided identities."]
    }

    func run(using context: CommandContext) throws -> Future<Void> {
        let email = try context.argument("email")
        let password = try context.requireOption("password")
        let passwordHash = try BCrypt.hash(password)
        let user = User(email: email, password: password)
        return user.save(on: context.container).map(to: Future<Void>) { user in
            return .done(on: context.container)
        }
    }
}

和上面一样,我想通过对context.container 执行查询来保存用户,但我得到了argument type 'Container' does not conform to expected type 'DatabaseConnectable' 错误。

如何在命令中访问数据库?

【问题讨论】:

    标签: vapor


    【解决方案1】:

    看来这可能是要走的路:

    func run(using context: CommandContext) throws -> EventLoopFuture<Void> {
        let email = try context.argument("email")
        let password = try context.requireOption("password")
        let passwordHash = try BCrypt.hash(password)
        let user = User(email: email, password: password)
    
        return context.container.withNewConnection(to: .psql) { db in
            return user.save(on: db).transform(to: ())
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-07
      • 1970-01-01
      • 2013-03-05
      • 2014-01-30
      • 2011-03-21
      • 1970-01-01
      相关资源
      最近更新 更多