Skip to content

Commit

Permalink
fix: fix method for get mongo connection
Browse files Browse the repository at this point in the history
  • Loading branch information
gulivero1773 committed Mar 7, 2024
1 parent 3ad7c32 commit 3f4aa59
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
//

import Vapor
import MongoKitten

extension Application {
/// A `MongoComponentsKey` conform to StorageKey protocol
Expand All @@ -37,3 +38,22 @@ extension Application {
set { storage[MongoComponentsKey.self] = newValue }
}
}

extension Application {
/// A `MongoClusterKey` conform to StorageKey protocol
public struct MongoClusterKey: StorageKey {
/// Less verbose typealias for `MongoCluster`.
public typealias Value = MongoCluster
}

/// Setup `mongoCluster` in application storage
public var mongoCluster: MongoCluster? {
get { storage[MongoClusterKey.self] }
set { storage[MongoClusterKey.self] = newValue }
}

/*
/// For example setup mongo cluster need use method like this:
app.mongoCluster = try await MongoCluster(connectingTo: ConnectionSettings(connectionString))
*/
}
12 changes: 5 additions & 7 deletions Services/MongoComponents/Sources/MongoComponents.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,12 @@ public struct MongoComponents: MongoComponentsProtocol {
public let app: Application

public func getConnection(by url: String) async -> MongoConnectionState {
do {
let mongoCluster = try await MongoCluster(connectingTo: ConnectionSettings(url))
let result = mongoCluster.connectionState
app.logger.debug("Connect to mongo have result: \(result)")
return result
} catch {
app.logger.error("ERROR: Connection to mongo db fail with error: \(error)")
let result = app.mongoCluster?.connectionState
app.logger.debug("Connect to mongo have result: \(String(describing: result))")
guard let result else {
app.logger.error("ERROR: Connection to mongo not found. Result: \(String(describing: result))")
return .disconnected
}
return result
}
}

0 comments on commit 3f4aa59

Please sign in to comment.