2016-04-25 05:20:55 +08:00
|
|
|
///<reference path="../../../typings/main.d.ts"/>
|
|
|
|
|
2016-05-05 04:06:52 +08:00
|
|
|
import * as mongoose from "mongoose";
|
2016-04-22 19:23:44 +08:00
|
|
|
import {Schema} from "mongoose";
|
2016-05-05 04:06:52 +08:00
|
|
|
|
|
|
|
export class DatabaseManager {
|
2016-04-22 19:23:44 +08:00
|
|
|
private static _instance:DatabaseManager = null;
|
|
|
|
private connectionError = false;
|
2016-05-05 04:06:52 +08:00
|
|
|
private errorObject = null;
|
|
|
|
private connectionOpen = false;
|
2016-04-22 19:23:44 +08:00
|
|
|
|
2016-05-05 04:06:52 +08:00
|
|
|
constructor() {
|
|
|
|
mongoose.connect('mongodb://localhost/EQZT6L');
|
2016-04-22 19:23:44 +08:00
|
|
|
}
|
|
|
|
|
2016-05-05 04:06:52 +08:00
|
|
|
public static getInstance(onError?:(err)=>void, onConnected?:() =>void) {
|
|
|
|
if (DatabaseManager._instance === null) {
|
|
|
|
DatabaseManager._instance = new DatabaseManager();
|
|
|
|
}
|
2016-04-22 19:23:44 +08:00
|
|
|
return DatabaseManager._instance;
|
|
|
|
}
|
|
|
|
|
2016-05-05 04:06:52 +08:00
|
|
|
public onConnectionError(onError:(err) => void){
|
|
|
|
if (this.connectionError === true) {
|
|
|
|
return onError(DatabaseManager._instance.errorObject);
|
|
|
|
}
|
|
|
|
mongoose.connection.once('error', (err) => {
|
|
|
|
this.connectionError = true;
|
|
|
|
this.errorObject = err;
|
|
|
|
onError(err);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
public onConnected(onConnected:() => void){
|
|
|
|
if (this.connectionOpen === true) {
|
|
|
|
return onConnected();
|
|
|
|
}
|
|
|
|
mongoose.connection.once('open', (err) => {
|
|
|
|
this.connectionOpen = true;
|
|
|
|
onConnected();
|
|
|
|
});
|
2016-04-22 19:23:44 +08:00
|
|
|
}
|
|
|
|
|
2016-05-05 04:06:52 +08:00
|
|
|
public getModel(name:string, schema:any) {
|
|
|
|
return mongoose.model(name, new Schema(schema));
|
|
|
|
}
|
|
|
|
|
|
|
|
public disconnect() {
|
2016-04-22 19:23:44 +08:00
|
|
|
mongoose.disconnect();
|
|
|
|
}
|
2016-05-05 04:06:52 +08:00
|
|
|
|
|
|
|
public isConnectionError() {
|
2016-04-22 19:23:44 +08:00
|
|
|
return this.connectionError;
|
|
|
|
}
|
|
|
|
}
|