2017-07-20 02:06:12 +07:00
|
|
|
|
|
|
|
import MongoDB = require("mongodb");
|
|
|
|
import { IMongoClient } from "./IMongoClient";
|
2018-08-19 21:51:36 +07:00
|
|
|
import Bluebird = require("bluebird");
|
|
|
|
import { AUTHENTICATION_FAILED } from "../../../../../shared/UserMessages";
|
|
|
|
import { IGlobalLogger } from "../../logging/IGlobalLogger";
|
2017-07-20 02:06:12 +07:00
|
|
|
|
|
|
|
export class MongoClient implements IMongoClient {
|
2018-08-19 21:51:36 +07:00
|
|
|
private url: string;
|
|
|
|
private databaseName: string;
|
2017-07-20 02:06:12 +07:00
|
|
|
|
2018-08-19 21:51:36 +07:00
|
|
|
private database: MongoDB.Db;
|
|
|
|
private client: MongoDB.MongoClient;
|
|
|
|
private logger: IGlobalLogger;
|
|
|
|
|
|
|
|
constructor(
|
|
|
|
url: string,
|
|
|
|
databaseName: string,
|
|
|
|
logger: IGlobalLogger) {
|
|
|
|
|
|
|
|
this.url = url;
|
|
|
|
this.databaseName = databaseName;
|
|
|
|
this.logger = logger;
|
|
|
|
}
|
|
|
|
|
|
|
|
connect(): Bluebird<void> {
|
|
|
|
const that = this;
|
|
|
|
const connectAsync = Bluebird.promisify(MongoDB.MongoClient.connect);
|
|
|
|
return connectAsync(this.url)
|
|
|
|
.then(function (client: MongoDB.MongoClient) {
|
|
|
|
that.database = client.db(that.databaseName);
|
|
|
|
that.database.on("close", () => {
|
|
|
|
that.logger.info("[MongoClient] Lost connection.");
|
|
|
|
});
|
|
|
|
that.database.on("reconnect", () => {
|
|
|
|
that.logger.info("[MongoClient] Reconnected.");
|
|
|
|
});
|
|
|
|
that.client = client;
|
|
|
|
});
|
2017-07-20 02:06:12 +07:00
|
|
|
}
|
|
|
|
|
2018-08-19 21:51:36 +07:00
|
|
|
close(): Bluebird<void> {
|
|
|
|
if (this.client) {
|
|
|
|
this.client.close();
|
|
|
|
this.database = undefined;
|
|
|
|
this.client = undefined;
|
|
|
|
}
|
|
|
|
return Bluebird.resolve();
|
|
|
|
}
|
|
|
|
|
|
|
|
collection(name: string): Bluebird<MongoDB.Collection> {
|
|
|
|
if (!this.client) {
|
|
|
|
const that = this;
|
|
|
|
return this.connect()
|
|
|
|
.then(() => Bluebird.resolve(that.database.collection(name)));
|
|
|
|
}
|
|
|
|
|
|
|
|
return Bluebird.resolve(this.database.collection(name));
|
2017-07-20 02:06:12 +07:00
|
|
|
}
|
|
|
|
}
|