Reputation: 710
I want to create a command in which you can create a user (like database seeds).
However, I cannot access a database in a command, my code is like the following:
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)
}
}
}
Like the above, I want to save users by executing a query on context.container
, but I got argument type 'Container' does not conform to expected type 'DatabaseConnectable'
Error.
How to access to the database in a command?
Upvotes: 4
Views: 193
Reputation: 511
It seems like this might be the way to go:
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: ())
}
}
Upvotes: 4