1
0
mirror of https://github.com/xuthus83/pigallery2.git synced 2025-01-14 14:43:17 +08:00
pigallery2/backend/model/mongoose/DatabaseManager.ts

53 lines
1.5 KiB
TypeScript
Raw Normal View History

2016-04-24 23:20:55 +02:00
///<reference path="../../../typings/main.d.ts"/>
2016-04-22 13:23:44 +02:00
import * as mongoose from 'mongoose';
import {Schema} from "mongoose";
export class DatabaseManager{
private static _instance:DatabaseManager = null;
private connectionError = false;
2016-04-24 20:56:54 +02:00
constructor(onError?:(err)=>void,onConnected?:() =>void){
2016-04-22 13:23:44 +02:00
mongoose.connection.on('error', function (err) {
this.connectionError = true;
if(onError){
onError(err);
}
});
2016-04-24 20:56:54 +02:00
mongoose.connection.on('connected', function () {
if(onConnected){
onConnected();
}
});
2016-04-22 13:23:44 +02:00
try {
mongoose.connect('mongodb://localhost/EQZT6L');
}catch(ex){
this.connectionError = true;
if(onError){
onError(ex);
}
}
}
2016-04-24 20:56:54 +02:00
public static getInstance(onError?:(err)=>void,onConnected?:() =>void){
2016-04-22 13:23:44 +02:00
if(DatabaseManager._instance === null){
2016-04-24 20:56:54 +02:00
DatabaseManager._instance = new DatabaseManager(onError,onConnected);
}else{
if(DatabaseManager._instance.connectionError === false && onConnected){
onConnected();
}
2016-04-22 13:23:44 +02:00
}
return DatabaseManager._instance;
}
public getModel(name:string,schema:any){
return mongoose.model(name,new Schema(schema));
}
public disconnect(){
mongoose.disconnect();
}
public isConnectionError(){
return this.connectionError;
}
}