我正在使用 Swift 5 和 Vapor 4 编写后端,数据库是 PostgreSQL 12。我有一个问题:如何在本地与数据库 (CRUD) 交互,而无需 POST 或 GET 请求?所有教程都展示了如何再次通过 HTTPS 仅基于 Request 进行 CRUD。我已经问过这个问题:Vapor 3 PostgreSQL CRUD without requests http ,但这 不是一个重复的问题,Vapor 4 的工作方式完全不同!请查看我当前的 Vapor 3 工作班(基于此答案:Is is possible to use Vapor 3 Postgres Fluent in a Standalone script?):
import Vapor
import FluentPostgreSQL
final class WorkWithPostgres {
private let databaseConfig = PostgreSQLDatabaseConfig(hostname: "localhost", port: 5432, username: "RutrackerTech", database: "vaporpostgres", password: "ru628trac4er")
let postgres: PostgreSQLDatabase
static let shared = WorkWithPostgres()
private init() {
postgres = PostgreSQLDatabase(config: databaseConfig)
}
/// Will it create undeleted memory leaks?
func shutdownGracefully(worker: MultiThreadedEventLoopGroup, completion: (() -> Void)?) {
worker.shutdownGracefully { error in
completion?()
}
}
/// Will it create udeleted memory leaks?
func connect(completion: ((MultiThreadedEventLoopGroup, PostgreSQLConnection) -> Void)?) {
let worker = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let eventLoopFuturePostgreSQLConnection = postgres.newConnection(on: worker)
let _ = eventLoopFuturePostgreSQLConnection.map { postgreSQLConnection in
completion?(worker, postgreSQLConnection)
}
}
func readAll<T: PostgreSQLModel>(postgreSQLModel: T.Type, completion: (([T]) -> Void)?) {
connect { worker, connection in
let _ = postgreSQLModel.query(on: connection).all().map { databaseData in
self.shutdownGracefully(worker: worker) {
completion?(databaseData)
}
}
}
}
func create<T: PostgreSQLModel>(postgreSQLModel: T) {
connect { worker, connection in
let _ = postgreSQLModel.save(on: connection).whenComplete {
self.shutdownGracefully(worker: worker, completion: nil)
}
}
}
}
最大的问题:我找不到PostgreSQLDatabase
inFluentPostgresDriver
或 in 的替代品Fluent
。或者,也许,应该是解决此任务的另一种方法?
感谢您的阅读,如果您有任何帮助或建议,我将不胜感激!