3

我正在使用 Xcode 11.2 和 Swift 5.1 基于 Vapor 3.1.10 创建后端,数据库是 PostgreSQL 12。我有一个问题:如何在没有 POST 和 GET 请求的情况下与数据库(CRUD)交互。所有教程都展示了如何仅基于请求通过 HTTPS 进行 CRUD。但是,如果我的应用需要在不与网络交互的情况下将某些内容保存在数据库中怎么办?看我的代码:

import Vapor
import FluentPostgreSQL

final class Device: PostgreSQLModel {        
    var id: Int?
    var isWorking: Bool
    var serial: Int

    init(isWorking: Bool, serial: Int) {
        self.isWorking = isWorking
        self.serial = serial
    }    
}
extension Device: Content {}
extension Device: Migration {}
extension Device: Parameter {}

经典的写或读方法是:

import Vapor

final class DeviceController {        
    func readAll(_ req: Request) throws -> Future<[Device]> {
        return Device.query(on: req).all()
    }

    func create(_ req: Request) throws -> Future<Device> {
        return try req.content.decode(Device.self).flatMap { device in
            return device.save(on: req)
        }
    }
}

如何替换req到我可以在本地创建的另一个后台安全线程?

例如:

let device = Device(isWorking: true, serial: 54321)
device.save(on: <#T##DatabaseConnectable#>)

如何更换<#T##DatabaseConnectable#>

我将感谢任何帮助或建议。

4

2 回答 2

1

RequestContainer,它有eventLoop,它是DatabaseConnectable

Application,它是Container,它有eventLoop,但它不是DatabaseConnectable

您如何使用Application数据库查询?

在任何Container你都可以获得到数据库的池连接,你可能猜到这个连接是DatabaseConnectable.

示例查询boot.swift

import Vapor
import FluentSQL
import FluentPostgreSQL

public func boot(_ app: Application) throws {
    let _ = app.requestPooledConnection(to: .psql).flatMap { conn in
        return User.query(conn).all().map { users in
            print("just found \(users.count) users")
        }.always {
            try? app.releasePooledConnection(conn, to: .psql)
        }
    }
}

.psql上面的代码将通过容器中的标识符请求与 PostgreSQL 的池连接Application,然后对该连接执行查询,然后在always阻塞中将该连接释放回池。

去哪里找Container后台任务?

如果您使用https://github.com/vapor/jobshttps://github.com/MihaelIsaev/VaporCron,您将Container在任务声明中有一个对象。

示例VaporCron

// in boot.swift
import Vapor
import VaporCron

/// Called after your application has initialized.
public func boot(_ app: Application) throws {
    scheduleTasks(on: app)
}

/// Scheduling Cron tasks
private func scheduleTasks(on app: Application) {
    do {
        _ = try VaporCron.schedule(Every1MinCheck.self, on: app)
    } catch {
        print("cron schedule error: \(error)")
    }
}

// in Every1MinCheck.swift
import Vapor
import VaporCron
import FluentSQL
import PostgreSQL

struct Every1MinCheck: VaporCronSchedulable {
    static var expression: String { return "*/1 * * * *" } // every 1 minute

    static func task(on container: VaporCronContainer) -> Future<Void> {
        return container.requestPooledConnection(to: .psql).flatMap { conn in
            return User.query(conn).all().map { users in
                print("just found \(users.count) users")
            }.always {
                try? container.releasePooledConnection(conn, to: .psql)
            }
        }
    }
}
于 2019-11-07T21:10:40.363 回答
0

基于这个问题和答案(Is is possible to use Vapor 3 Postgres Fluent in a Standalone script?)我意识到CRUD是这样的:

import Vapor
import FluentPostgreSQL

final class Device: PostgreSQLModel {
    var id: Int?
    var isWorking: Bool
    var serial: Int

    init(isWorking: Bool, serial: Int) {
        self.isWorking = isWorking
        self.serial = serial
    }
}
extension Device: Content {}
extension Device: Migration {}
extension Device: Parameter {}

final class WorkWithPostgres {

    let databaseConfig = PostgreSQLDatabaseConfig(hostname: "localhost", port: 5432, username: "username", database: "testestest", password: nil)

    let database: PostgreSQLDatabase

    static let shared = WorkWithPostgres()

    private init() {
        database = PostgreSQLDatabase(config: databaseConfig)
    }

    func readAll<T: PostgreSQLModel>(postgreSQLModel: T.Type, completion: (([T]) -> Void)?) {
        let worker = MultiThreadedEventLoopGroup(numberOfThreads: 1)
        let conn = database.newConnection(on: worker)

        let _ = conn.map { connection in
            postgreSQLModel.query(on: connection).all().map { databaseData in
                worker.shutdownGracefully { _ in
                }

                completion?(databaseData)
            }
        }
    }

    func create<T: PostgreSQLModel>(postgreSQLModel: T) {
        let worker = MultiThreadedEventLoopGroup(numberOfThreads: 1)
        let conn = database.newConnection(on: worker)

        let _ = conn.map { connection in
            let _ = postgreSQLModel.save(on: connection).whenComplete {
                worker.shutdownGracefully { _ in
                }
            }
        }
    }

}

final class DeviceController {

    func readAll(completion: (([Device]) -> Void)?) {
        WorkWithPostgres.shared.readAll(postgreSQLModel: Device.self) { devices in
            completion?(devices)
        }
    }

    func create(isWorking: Bool, serial: Int) {
        let device = Device(isWorking: isWorking, serial: serial)

        WorkWithPostgres.shared.create(postgreSQLModel: device)
    }

}

它正在工作,但我不确定它是否是这样做的好方法。有人知道吗?

于 2020-02-05T17:36:46.667 回答