[Vapor3] How to access DB in a custom command

[10/27, 2018]

日本語 / English

I still have not understood what custom command is for yet? But I think it is for registering admin user or register default setting by custom command.

How to access?

CommandContext has container that can call withNewConnection. So you can get the DatabaseConnectable object like this below.

func run(using context: CommandContext) throws -> Future<Void> {

    let name = try context.argument("name")
    let email = try context.argument("email")
    let password = try context.argument("password")
    let hash = try BCrypt.hash(password)

    let container = context.container
    return container.withNewConnection(to: .mysql) {
            conn in            
            //conn <- DatabaseConnectable object
            let admin = User(name: name, email: email, passwordHash: hash)
            return [admin.create(on: conn)].flatten(on: container).transform(to: ())

This is just a sample. So you might need to check something that a user exists or not before you register and so on.

This is the source code I developed. Github