Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do I get the database object using Vapor?

I feel like this should be straight forward, however I'm not able to find a solution.

I'm creating a server using Vapor with a postgres database. I'm trying to write the class to query and store data in the database

However when looking at the docs:

let planets = try await Planet.query(on: database)
.filter(\.$type == .gasGiant)
.sort(\.$name)
.with(\.$star)
.all()

In this example where do I get the database object in order to perform a query like this?

The only place I've been able to find from online examples is like such:

app.post("planets") { req -> EventLoopFuture<Planet> in
    
    let planet = try req.content.decode(Planet.self)
    return planet.create(on: req.db).map { planet }
}

When you add a route, you get the request object back which has .db

But in my case the requests are not originating from a post request, or a http request but from a websocket, and there doesn't appear be a database or request object on the Vapor WebSocket bits

What am I missing?

like image 480
GP89 Avatar asked Apr 06 '26 23:04

GP89


1 Answers

I'm not sure how I missed it before, but it is accessible with

app.db
like image 200
GP89 Avatar answered Apr 09 '26 13:04

GP89



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!