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

55 lines
1.5 KiB
TypeScript
Raw Normal View History

2016-04-24 23:20:55 +02:00
///<reference path="../../../typings/main.d.ts"/>
import * as mongoose from "mongoose";
2016-04-22 13:23:44 +02:00
import {Schema} from "mongoose";
export class DatabaseManager {
2016-04-22 13:23:44 +02:00
private static _instance:DatabaseManager = null;
private connectionError = false;
private errorObject = null;
private connectionOpen = false;
2016-04-22 13:23:44 +02:00
constructor() {
mongoose.connect('mongodb://localhost/EQZT6L');
2016-04-22 13:23:44 +02:00
}
public static getInstance(onError?:(err)=>void, onConnected?:() =>void) {
if (DatabaseManager._instance === null) {
DatabaseManager._instance = new DatabaseManager();
}
2016-04-22 13:23:44 +02:00
return DatabaseManager._instance;
}
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 13:23:44 +02:00
}
public getModel(name:string, schema:any) {
return mongoose.model(name, new Schema(schema));
}
public disconnect() {
2016-04-22 13:23:44 +02:00
mongoose.disconnect();
}
public isConnectionError() {
2016-04-22 13:23:44 +02:00
return this.connectionError;
}
}