我想创建一个命令,您可以在其中创建用户(如数据库种子)。
但是,我无法在命令中访问数据库,我的代码如下:
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'
错误。
如何在命令中访问数据库?
答案 0 :(得分:4)
似乎这可能是要走的路:
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: ())
}
}