GP89
GP89

Reputation: 6740

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?

Upvotes: 4

Views: 585

Answers (1)

GP89
GP89

Reputation: 6740

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

app.db

Upvotes: 1

Related Questions