2020-01-11 19:42:28 +00:00
|
|
|
//
|
|
|
|
// MongoController.swift
|
|
|
|
// MongoView
|
|
|
|
//
|
|
|
|
// Created by Shadowfacts on 1/8/20.
|
|
|
|
// Copyright © 2020 Shadowfacts. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
import MongoSwift
|
|
|
|
import NIO
|
|
|
|
|
|
|
|
class MongoController {
|
|
|
|
let connectionString: String
|
|
|
|
|
|
|
|
var group: EventLoopGroup!
|
|
|
|
|
|
|
|
var client: MongoClient!
|
2020-04-01 23:37:00 +00:00
|
|
|
|
|
|
|
var status: Status = .connecting {
|
|
|
|
didSet {
|
|
|
|
statusDidChange.forEach { $0(status) }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
var statusDidChange = [(Status) -> Void]()
|
2020-01-11 19:42:28 +00:00
|
|
|
|
|
|
|
init(connectionString: String) {
|
|
|
|
self.connectionString = connectionString
|
|
|
|
}
|
|
|
|
|
|
|
|
deinit {
|
|
|
|
try! group.syncShutdownGracefully()
|
|
|
|
cleanupMongoSwift()
|
|
|
|
}
|
|
|
|
|
|
|
|
func setup() {
|
|
|
|
print("setting up mongo")
|
|
|
|
|
|
|
|
group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
|
|
|
|
2020-04-01 23:37:00 +00:00
|
|
|
do {
|
|
|
|
client = try MongoClient(connectionString, using: group)
|
|
|
|
status = .success
|
|
|
|
} catch {
|
|
|
|
status = .failed
|
|
|
|
print("Failed to connect to Mongo: \(error)")
|
|
|
|
}
|
2020-01-11 19:42:28 +00:00
|
|
|
}
|
2020-02-10 02:13:22 +00:00
|
|
|
|
|
|
|
func db(for collection: DatabaseCollection) -> MongoDatabase {
|
|
|
|
return client.db(collection.database)
|
|
|
|
}
|
|
|
|
|
|
|
|
func collection(_ collection: DatabaseCollection) -> MongoCollection<Document> {
|
|
|
|
return db(for: collection).collection(collection.name)
|
|
|
|
}
|
2020-01-11 19:42:28 +00:00
|
|
|
|
|
|
|
}
|
2020-04-01 23:37:00 +00:00
|
|
|
|
|
|
|
extension MongoController {
|
|
|
|
enum Status {
|
|
|
|
case connecting, success, failed
|
|
|
|
}
|
|
|
|
}
|