1
0
mirror of https://github.com/bpatrik/pigallery2.git synced 2025-01-26 05:27:35 +02:00

implementing mongoose managers

This commit is contained in:
Braun Patrik 2016-04-22 13:23:44 +02:00
parent 4a44f232a8
commit bba7479184
24 changed files with 364 additions and 68 deletions

View File

@ -1,6 +1,10 @@
import {ConfigLoader} from "./ConfigLoader";
export enum DatabaseType{
memory, mongoDB
}
export class ConfigClass{
constructor(){
@ -12,6 +16,7 @@ export class ConfigClass{
public thumbnailSizes:Array<number> = [200];
public imagesFolder:string = "/demo/images";
public thumbnailFolder:string = "/demo/TEMP";
public databaseType:DatabaseType = DatabaseType.mongoDB;
}

View File

@ -2,10 +2,10 @@
///<reference path="../../typings/main.d.ts"/>
import {UserManager} from "../model/UserManager";
import {NextFunction, Request, Response} from "express";
import {Error, ErrorCodes} from "../../common/entities/Error";
import {UserRoles} from "../../common/entities/User";
import {ObjectManagerRepository} from "../model/ObjectManagerRepository";
export class AuthenticationMWs {
@ -40,10 +40,9 @@ export class AuthenticationMWs {
(typeof req.body.loginCredential.password === 'undefined')) {
return next();
}
//lets find the user
UserManager.findOne({
username: req.body.loginCredential.username,
ObjectManagerRepository.getInstance().getUserManager().findOne({
name: req.body.loginCredential.username,
password: req.body.loginCredential.password
}, (err, result) => {
if ((err) || (!result)) {

View File

@ -3,9 +3,10 @@ import * as path from 'path';
import * as fs from 'fs';
import {NextFunction, Request, Response} from "express";
import {Error, ErrorCodes} from "../../common/entities/Error";
import {GalleryManager} from "../model/GalleryManager";
import {GalleryManager} from "../model/memory/GalleryManager";
import {Directory} from "../../common/entities/Directory";
import {Config} from "../config/Config";
import {ObjectManagerRepository} from "../model/ObjectManagerRepository";
export class GalleryMWs {
@ -22,7 +23,7 @@ export class GalleryMWs {
return next();
}
GalleryManager.listDirectory(directoryName,(err,directory:Directory) => {
ObjectManagerRepository.getInstance().getGalleryManager().listDirectory(directoryName,(err,directory:Directory) => {
if(err || !directory){
return next(new Error(ErrorCodes.GENERAL_ERROR,err));
}

View File

@ -1,7 +1,8 @@
import {UserManager} from "../model/UserManager";
import {UserManager} from "../model/memory/UserManager";
import {NextFunction, Request, Response} from "express";
import {Error, ErrorCodes} from "../../common/entities/Error";
import {ObjectManagerRepository} from "../model/ObjectManagerRepository";
export class UserMWs {
@ -12,8 +13,8 @@ export class UserMWs {
|| (typeof req.body.userModReq.newPassword === 'undefined')) {
return next();
}
UserManager.changePassword(req.body.userModReq, (err, result) =>{
ObjectManagerRepository.getInstance().getUserManager().changePassword(req.body.userModReq, (err, result) =>{
if ((err) || (!result)) {
return next(new Error(ErrorCodes.GENERAL_ERROR));
}
@ -28,7 +29,7 @@ export class UserMWs {
return next();
}
UserManager.createUser(req.body.newUser, (err, result) =>{
ObjectManagerRepository.getInstance().getUserManager().createUser(req.body.newUser, (err, result) =>{
if ((err) || (!result)) {
return next(new Error(ErrorCodes.USER_CREATION_ERROR));
}
@ -44,7 +45,7 @@ export class UserMWs {
return next();
}
UserManager.deleteUser(req.body.userModReq.id, (err, result) =>{
ObjectManagerRepository.getInstance().getUserManager().deleteUser(req.body.userModReq.id, (err, result) =>{
if ((err) || (!result)) {
return next(new Error(ErrorCodes.GENERAL_ERROR));
}
@ -62,8 +63,8 @@ export class UserMWs {
return next();
}
UserManager.changeRole(req.body.userModReq, (err, result) =>{
if ((err) || (!result)) {
ObjectManagerRepository.getInstance().getUserManager().changeRole(req.body.userModReq, (err) =>{
if (err) {
return next(new Error(ErrorCodes.GENERAL_ERROR));
}
@ -73,7 +74,7 @@ export class UserMWs {
public static listUsers(req:Request, res:Response, next:NextFunction){
UserManager.find({}, (err, result) =>{
ObjectManagerRepository.getInstance().getUserManager().find({}, (err, result) =>{
if ((err) || (!result)) {
return next(new Error(ErrorCodes.GENERAL_ERROR));
}

View File

@ -1,8 +1,9 @@
import {UserManager} from "../model/UserManager";
import {UserManager} from "../model/memory/UserManager";
import {NextFunction, Request, Response} from "express";
import {Error, ErrorCodes} from "../../common/entities/Error";
import {UserRoles} from "../../common/entities/User";
import {ObjectManagerRepository} from "../model/ObjectManagerRepository";
export class UserRequestConstrainsMWs {
@ -40,7 +41,7 @@ export class UserRequestConstrainsMWs {
return next();
}
UserManager.find({minRole:UserRoles.Admin}, (err, result) =>{
ObjectManagerRepository.getInstance().getUserManager().find({minRole:UserRoles.Admin}, (err, result) =>{
if ((err) || (!result)) {
return next(new Error(ErrorCodes.GENERAL_ERROR));
}

View File

@ -6,10 +6,9 @@ import * as sizeOf from 'image-size';
import {Directory} from "../../common/entities/Directory";
import {Photo} from "../../common/entities/Photo";
export class GalleryManager {
public static listDirectory(relativeDirectoryName, cb:(error: any,result:Directory) => void){
export class DiskManager{
public static scanDirectory(relativeDirectoryName, cb:(error: any, result:Directory) => void){
console.log("DiskManager: scanDirectory");
let directoryName = path.basename(relativeDirectoryName);
let directoryParent = path.join( path.dirname(relativeDirectoryName),"/");
let absoluteDirectoryName = path.join(__dirname,"/../../demo/images", relativeDirectoryName);
@ -30,7 +29,7 @@ export class GalleryManager {
directory.directories.push(new Directory(2,file,relativeDirectoryName,new Date(),[],[]));
}
if(GalleryManager.isImage(fullFilePath)){
if(DiskManager.isImage(fullFilePath)){
let dimensions = sizeOf(fullFilePath);
directory.photos.push(new Photo(1,file,dimensions.width,dimensions.height));
}
@ -62,5 +61,4 @@ export class GalleryManager {
return false;
}
}

View File

@ -0,0 +1,4 @@
import {Directory} from "../../common/entities/Directory";
export interface IGalleryManager {
listDirectory(relativeDirectoryName, cb:(error: any,result:Directory) => void);
}

View File

@ -0,0 +1,9 @@
import {User} from "../../common/entities/User";
export interface IUserManager {
findOne(filter,cb:(error: any,result:User) => void);
find(filter,cb:(error: any,result:Array<User>) => void);
createUser(user,cb:(error: any,result:User) => void);
deleteUser(id:number,cb:(error: any,result:string) => void);
changeRole(request:any,cb:(error: any) => void);
changePassword(request:any,cb:(error: any,result:string) => void);
}

View File

@ -0,0 +1,47 @@
import {IUserManager} from "./IUserManager";
import {IGalleryManager} from "./IGalleryManager";
import {MongoGalleryManager} from "./mongoose/MongoGalleryManager";
import {MongoUserManager} from "./mongoose/MongoUserManager";
import {GalleryManager} from "./memory/GalleryManager";
import {UserManager} from "./memory/UserManager";
export class ObjectManagerRepository{
private _galleryManager:IGalleryManager;
private _userManager:IUserManager;
private static _instance:ObjectManagerRepository = null;
public static InitMongoManagers(){
ObjectManagerRepository.getInstance().setGalleryManager(new MongoGalleryManager());
ObjectManagerRepository.getInstance().setUserManager(new MongoUserManager());
}
public static MemoryMongoManagers(){
ObjectManagerRepository.getInstance().setGalleryManager(new GalleryManager());
ObjectManagerRepository.getInstance().setUserManager(new UserManager());
}
public static getInstance(){
if(this._instance === null){
this._instance = new ObjectManagerRepository();
}
return this._instance;
}
getGalleryManager():IGalleryManager {
return this._galleryManager;
}
setGalleryManager(value:IGalleryManager) {
this._galleryManager = value;
}
getUserManager():IUserManager {
return this._userManager;
}
setUserManager(value:IUserManager) {
this._userManager = value;
}
}

View File

@ -1,32 +0,0 @@
import {User} from "../../common/entities/User";
export class UserManager {
private static users = [new User(1,"TestUser","test@test.hu","122345")];
public static findOne(filter,cb:(error: any,result:User) => void){
return cb(null, UserManager.users[0]);
}
public static find(filter,cb:(error: any,result:Array<User>) => void){
return cb(null, UserManager.users);
}
public static createUser(user,cb:(error: any,result:User) => void){
UserManager.users.push(user);
return cb(null, user);
}
public static deleteUser(id:number,cb:(error: any,result:string) => void){
UserManager.users = UserManager.users.filter(u => u.id != id);
return cb(null, "ok");
}
public static changeRole(request:any,cb:(error: any,result:string) => void){
return cb(null,"ok");
}
public static changePassword(request:any,cb:(error: any,result:string) => void){
return cb(null,"ok");
}
}

View File

@ -0,0 +1,14 @@
import {Directory} from "../../../common/entities/Directory";
import {IGalleryManager} from "../IGalleryManager";
import {DiskManager} from "../DiskManger";
export class GalleryManager implements IGalleryManager{
public listDirectory(relativeDirectoryName, cb:(error: any,result:Directory) => void){
return DiskManager.scanDirectory(relativeDirectoryName,cb);
}
}

View File

@ -0,0 +1,33 @@
import {User} from "../../../common/entities/User";
import {IUserManager} from "../IUserManager";
export class UserManager implements IUserManager{
private users = [new User(1,"TestUser","test@test.hu","122345")];
public findOne(filter,cb:(error: any,result:User) => void){
return cb(null, this.users[0]);
}
public find(filter,cb:(error: any,result:Array<User>) => void){
return cb(null, this.users);
}
public createUser(user,cb:(error: any,result:User) => void){
this.users.push(user);
return cb(null, user);
}
public deleteUser(id:number,cb:(error: any) => void){
this.users = this.users.filter(u => u.id != id);
return cb(null);
}
public changeRole(request:any,cb:(error: any,result:string) => void){
throw new Error("not implemented"); //TODO: implement
}
public changePassword(request:any,cb:(error: any,result:string) => void){
throw new Error("not implemented"); //TODO: implement
}
}

View File

@ -0,0 +1,42 @@
import * as mongoose from 'mongoose';
import {Schema} from "mongoose";
export class DatabaseManager{
private static _instance:DatabaseManager = null;
private connectionError = false;
constructor(onError?:(err)=>void){
mongoose.connection.on('error', function (err) {
this.connectionError = true;
if(onError){
onError(err);
}
});
try {
mongoose.connect('mongodb://localhost/EQZT6L');
}catch(ex){
this.connectionError = true;
if(onError){
onError(ex);
}
}
}
public static getInstance(onError?:(err)=>void){
if(DatabaseManager._instance === null){
DatabaseManager._instance = new DatabaseManager(onError);
}
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;
}
}

View File

@ -0,0 +1,80 @@
import * as fs from 'fs';
import * as path from 'path';
import * as mime from 'mime';
import * as sizeOf from 'image-size';
import {Schema} from "mongoose";
import {Directory} from "../../../common/entities/Directory";
import {Photo} from "../../../common/entities/Photo";
import {IGalleryManager} from "../IGalleryManager";
import {DatabaseManager} from "./DatabaseManager";
import {DiskManager} from "../DiskManger";
import {Utils} from "../../../common/Utils";
export class MongoGalleryManager implements IGalleryManager{
private DirectoryModel;
private PhotoModel;
constructor(){
this.DirectoryModel = DatabaseManager.getInstance().getModel('directory',{
name:String,
path:String,
lastUpdate:Date,
directories: [{
type: Schema.Types.ObjectId,
ref: 'directory'
}],
photos: [{
type: Schema.Types.ObjectId,
ref: 'photo'
}]
});
this.PhotoModel = DatabaseManager.getInstance().getModel('photo',{
name:String,
width:Number,
height:Number
});
}
public listDirectory(relativeDirectoryName, cb:(error: any,result:Directory) => void){
let directoryName = path.basename(relativeDirectoryName);
let directoryParent = path.join( path.dirname(relativeDirectoryName),"/");
this.DirectoryModel.findOne({name:directoryName, path: directoryParent}).populate('photos').populate('directories').exec( (err,res) =>{
if(err || !res){
return this.indexDirectory(relativeDirectoryName,cb);
}
return cb(err,res);
});
}
public indexDirectory(relativeDirectoryName, cb:(error: any,result:Directory) => void){
DiskManager.scanDirectory(relativeDirectoryName,(err,scannedDirectory)=>{
let arr = [];
scannedDirectory.directories.forEach((value) => {
let dir = new this.DirectoryModel(value);
Utils.setKeys(dir,value);
dir.save();
arr.push(dir);
});
scannedDirectory.directories = arr;
arr = [];
scannedDirectory.photos.forEach((value) => {
let p = new this.PhotoModel(value);
Utils.setKeys(p,value);
p.save();
arr.push(p);
});
scannedDirectory.photos = arr;
this.DirectoryModel.create(scannedDirectory,(err)=>{
return cb(err,scannedDirectory);
});
});
}
}

View File

@ -0,0 +1,45 @@
import {User} from "../../../common/entities/User";
import {IUserManager} from "../IUserManager";
import {DatabaseManager} from "./DatabaseManager";
export class MongoUserManager implements IUserManager{
private UserModel;
constructor(){
this.UserModel = DatabaseManager.getInstance().getModel('user',{
name:String,
email:{ type: String, index: { unique: true }},
password:String,
role:Number
});
}
public findOne(filter,cb:(error: any,result:User) => void){
return this.UserModel.findOne(filter,function (err, result) {
return cb(err, result);
});
}
public find(filter,cb:(error: any,result:Array<User>) => void){
this.UserModel.find(filter,function (err, result) {
return cb(err, result);
});
}
public createUser(user,cb:(error: any,result:User) => void){
this.UserModel.create(user,cb);
}
public deleteUser(id:number,cb:(error: any) => void){
this.UserModel.remove({id:id},cb);
}
public changeRole(request:any,cb:(error: any,result:string) => void){
throw new Error("not implemented"); //TODO: implement
}
public changePassword(request:any,cb:(error: any,result:string) => void){
throw new Error("not implemented"); //TODO: implement
}
}

View File

@ -6,6 +6,7 @@ export class ErrorRouter{
constructor(private app) {
this.addApiErrorHandler();
this.addGenericHandler();
}
private addApiErrorHandler() {

View File

@ -11,7 +11,11 @@ import {GalleryRouter} from "./routes/GalleryRouter";
import {AdminRouter} from "./routes/AdminRouter";
import {ErrorRouter} from "./routes/ErrorRouter";
import {SharingRouter} from "./routes/SharingRouter";
import {Config} from "./config/Config";
import {Config, DatabaseType} from "./config/Config";
import {ObjectManagerRepository} from "./model/ObjectManagerRepository";
import {MongoGalleryManager} from "./model/mongoose/MongoGalleryManager";
import {MongoUserManager} from "./model/mongoose/MongoUserManager";
import {DatabaseManager} from "./model/mongoose/DatabaseManager";
export class Server {
@ -52,10 +56,21 @@ export class Server {
*/
// for parsing application/json
this.app.use(_bodyParser.json());
if(Config.databaseType === DatabaseType.memory){
ObjectManagerRepository.MemoryMongoManagers();
}else {
if (DatabaseManager.getInstance(()=>{
console.error("MongoDB connection error. Falling back to memory Object Managers");
ObjectManagerRepository.MemoryMongoManagers();
}).isConnectionError()) {
console.error("MongoDB connection error. Falling back to memory Object Managers");
ObjectManagerRepository.MemoryMongoManagers();
} else {
ObjectManagerRepository.InitMongoManagers();
}
}
new PublicRouter(this.app);

View File

@ -19,4 +19,27 @@ export class Utils {
return url.substring(0, url.length - 1);
}
public static updateKeys(targetObject,sourceObject){
Object.keys(sourceObject).forEach((key)=> {
if(typeof targetObject[key] === "undefined"){
return;
}
if(typeof targetObject[key] === "object"){
Utils.updateKeys(targetObject[key],sourceObject[key] );
}else {
targetObject[key] = sourceObject[key];
}
});
}
public static setKeys(targetObject,sourceObject){
Object.keys(sourceObject).forEach((key)=> {
if(typeof targetObject[key] === "object"){
Utils.updateKeys(targetObject[key],sourceObject[key] );
}else {
targetObject[key] = sourceObject[key];
}
});
}
}

View File

@ -1,4 +1,4 @@
export class Photo{
constructor(public id:number,public name:string,public width:number,public height:number){}
export class Photo {
constructor(public id:number, public name:string, public width:number, public height:number) {
}
}

View File

@ -2,7 +2,6 @@
<md-sidenav name="menu" align="left" layout="column">
<md-toolbar class="md-theme-light">
<img width="25px" src="/icon.png"/>
<h1 class="md-toolbar-tools">PiGallery2</h1>
</md-toolbar>
<md-content layout-padding>

View File

@ -14,7 +14,7 @@
<md-input-container class="md-block" flex-gt-sm>
<label>Password</label>
<input md-input type="password" [(value)]="loginCredential.password"
ngControl="name" #name="ngForm" required>
ngControl="password" #name="ngForm" required>
</md-input-container>
</form>
</md-card-content>

View File

@ -8,10 +8,11 @@
"license": "MIT",
"main": "./backend/server.js",
"scripts": {
"install": "typings install && tsc -p backend && tsc -p common && webpack --config ./frontend/webpack.config.js ",
"install": "typings install && tsc -p backend && tsc -p test/backend && tsc -p common && webpack --config ./frontend/webpack.config.js ",
"pretest": "typings install",
"test": "karma start ./karma.conf.js",
"start": "node ./backend/server"
"start": "node ./backend/server",
"postinstall": "node ./test/backend/initMongo.js"
},
"repository": {
"type": "git",
@ -30,9 +31,10 @@
"express-session": "^1.13.0",
"html-webpack-plugin": "^2.16.0",
"image-size": "^0.5.0",
"jimp": "^0.2.21",
"karma-mocha-reporter": "^2.0.1",
"jimp": "^0.2.22",
"karma-mocha-reporter": "^2.0.2",
"mime": "^1.3.4",
"mongoose": "^4.4.13",
"morgan": "^1.7.0",
"ng2-cookies": "^0.1.5",
"ng2-material": "^0.3.6",
@ -41,11 +43,11 @@
"rxjs": "5.0.0-beta.2",
"style-loader": "^0.13.1",
"ts-loader": "^0.8.2",
"tslint": "^3.7.4",
"tslint": "^3.8.0",
"typescript": "^1.8.10",
"typings": "^0.7.9",
"webpack": "^1.13.0",
"zone.js": "^0.6.11"
"zone.js": "^0.6.12"
},
"devDependencies": {
"compression-webpack-plugin": "^0.3.0",

View File

@ -0,0 +1,8 @@
import {MongoUserManager} from "../../backend/model/mongoose/MongoUserManager";
import {User, UserRoles} from "../../common/entities/User";
import {DatabaseManager} from "../../backend/model/mongoose/DatabaseManager";
let userManager = new MongoUserManager();
userManager.createUser(new User(0,"demo","demo@demo.hu","demo",UserRoles.Developer),(err)=>{
DatabaseManager.getInstance().disconnect();
});

View File

@ -9,6 +9,7 @@
"image-size": "registry:dt/image-size#0.0.0+20160223165602",
"jasmine": "github:DefinitelyTyped/DefinitelyTyped/jasmine/jasmine.d.ts#d22516f9f089de107d7e7d5938566377370631f6",
"mime": "github:DefinitelyTyped/DefinitelyTyped/mime/mime.d.ts#0d622d857f97d44ea7dcad2b3edec1f23c48fe9e",
"mongoose": "registry:dt/mongoose#3.8.5+20160316155526",
"node": "github:DefinitelyTyped/DefinitelyTyped/node/node.d.ts#0d622d857f97d44ea7dcad2b3edec1f23c48fe9e",
"optimist": "registry:dt/optimist#0.0.0+20160316171810",
"serve-static": "github:DefinitelyTyped/DefinitelyTyped/serve-static/serve-static.d.ts#0d622d857f97d44ea7dcad2b3edec1f23c48fe9e"