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!
So, correct idea not to work with database like I did with Vapor 3. Now, in Vapor 4, you should use Database
instance. Where to get it? I can suggest 2 options for you. First is boot(_ app: Application)
in boot.swift
or in configure(_ app: Application)
in configure.swift
. So app
will have options to work with database like this: <Model>.query(on: app.db)
. Second option is req
in any request. req
should be of type Request
, like this: <Model>.query(on: req.db)
. By Model
, you can take any class inherited of class Model
, for example: final class User: Model, Content {
You should organise your code to be called from boot.swift
or configure.swift
or from any request, for example, in routes.swift