问题
I am writing backend using Swift 5 and Vapor 4, database is PostgreSQL 12. I have a question: how to interact with database (CRUD) locally, without POST or GET requests? All tutorials show how to CRUD only based on Request through HTTPS again. I already asked this question: Vapor 3 PostgreSQL CRUD without requests http BUT IT'S NOT A DUPLICATE QUESTION, Vapor 4 works completely different! Please, look at my current, working class for Vapor 3 (based on this answer: 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)
}
}
}
}
The biggest problem: I cannot find replacement to PostgreSQLDatabase
in FluentPostgresDriver
or in Fluent
.
Or, maybe, should be another approach to solve this task?
Thank you for reading, I will be thankful for any help or advice!
回答1:
There's no such thing as a connection in Fluent 4 - you can just use the database
type. So your model.save(on:)
becomes model.save(on: database)
来源:https://stackoverflow.com/questions/62560531/vapor-4-postgresql-crud-without-http-requests