Dependency injection of models to controllers, export controllers from app.js

This commit is contained in:
C. Fuhrman 2024-10-02 10:23:56 -04:00
parent 5815cd725a
commit 0fe07b84c6
14 changed files with 250 additions and 215 deletions

View file

@ -98,8 +98,9 @@ const Dashboard: React.FC = () => {
setQuizzes(quizzes as QuizType[]);
}
else {
console.log("show some quizes")
console.log("show some quizzes")
const folderQuizzes = await ApiService.getFolderContent(selectedFolder);
console.log("folderQuizzes: ", folderQuizzes);
setQuizzes(folderQuizzes as QuizType[]);
}
@ -147,7 +148,7 @@ const Dashboard: React.FC = () => {
setQuizzes(quizzes as QuizType[]);
}
else {
console.log("show some quizes")
console.log("show some quizzes")
const folderQuizzes = await ApiService.getFolderContent(selectedFolder);
setQuizzes(folderQuizzes as QuizType[]);

View file

@ -7,7 +7,35 @@ const dotenv = require('dotenv')
const { setupWebsocket } = require("./socket/socket");
const { Server } = require("socket.io");
//import routers
// instantiate the db
const db = require('./config/db.js');
// instantiate the models
const users = require('./models/users.js');
const userModel = new users(db);
const quiz = require('./models/quiz.js');
const quizModel = new quiz(db);
const folders = require('./models/folders.js');
const foldersModel = new folders(db, quizModel);
const images = require('./models/images.js');
const imageModel = new images(db);
// instantiate the controllers
const usersController = require('./controllers/users.js');
const usersControllerInstance = new usersController(userModel);
const foldersController = require('./controllers/folders.js');
const foldersControllerInstance = new foldersController(foldersModel);
const quizController = require('./controllers/quiz.js');
const quizControllerInstance = new quizController(quizModel, foldersModel);
const imagesController = require('./controllers/images.js');
const imagesControllerInstance = new imagesController(imageModel);
// export the controllers
module.exports.users = usersControllerInstance;
module.exports.folders = foldersControllerInstance;
module.exports.quizzes = quizControllerInstance;
module.exports.images = imagesControllerInstance;
//import routers (instantiate controllers as side effect)
const userRouter = require('./routers/users.js');
const folderRouter = require('./routers/folders.js');
const quizRouter = require('./routers/quiz.js');
@ -15,7 +43,6 @@ const imagesRouter = require('./routers/images.js')
// Setup environement
dotenv.config();
const db = require('./config/db.js');
const errorHandler = require("./middleware/errorHandler.js");
// Start app

View file

@ -8,10 +8,11 @@ const { MISSING_REQUIRED_PARAMETER, NOT_IMPLEMENTED, FOLDER_NOT_FOUND, FOLDER_AL
// controllers must use arrow functions to bind 'this' to the class instance in order to access class properties as callbacks in Express
class FoldersController {
constructor() {
constructor(foldersModel) {
console.log("FoldersController constructor: db", db)
this.db = db;
this.folders = new model(this.db);
this.folders = foldersModel;
// this.quizzes = quizModel;
console.log("FoldersController constructor: folders", this.folders);
}
@ -266,4 +267,4 @@ class FoldersController {
module.exports = new FoldersController;
module.exports = FoldersController;

View file

@ -5,7 +5,12 @@ const { MISSING_REQUIRED_PARAMETER, IMAGE_NOT_FOUND } = require('../constants/er
class ImagesController {
async upload(req, res, next) {
constructor(imagesModel) {
this.images = imagesModel;
console.log("ImagesController constructor: images", this.images);
}
upload = async (req, res, next) => {
try {
const file = req.file;
@ -13,19 +18,17 @@ class ImagesController {
throw new AppError(MISSING_REQUIRED_PARAMETER);
}
const id = await model.upload(file, req.user.userId);
const id = await this.images.upload(file, req.user.userId);
return res.status(200).json({
id: id
});
}
catch (error) {
} catch (error) {
return next(error);
}
};
}
async get(req, res, next) {
get = async (req, res, next) => {
try {
const { id } = req.params;
@ -33,10 +36,10 @@ class ImagesController {
throw new AppError(MISSING_REQUIRED_PARAMETER);
}
const image = await model.get(id);
const image = await this.images.get(id);
if (!image) {
throw new AppError(IMAGE_NOT_FOUND)
throw new AppError(IMAGE_NOT_FOUND);
}
// Set Headers for display in browser
@ -45,12 +48,11 @@ class ImagesController {
res.setHeader('Accept-Ranges', 'bytes');
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
return res.send(image.file_content);
}
catch (error) {
} catch (error) {
return next(error);
}
}
};
}
module.exports = new ImagesController;
module.exports = ImagesController;

View file

@ -1,13 +1,21 @@
const model = require('../models/quiz.js');
const folderModel = require('../models/folders.js');
// const model = require('../models/quiz.js');
const emailer = require('../config/email.js');
//const foldersController = require('./folders.js');
// const db = require('../config/db.js');
const AppError = require('../middleware/AppError.js');
const { MISSING_REQUIRED_PARAMETER, NOT_IMPLEMENTED, QUIZ_NOT_FOUND, FOLDER_NOT_FOUND, QUIZ_ALREADY_EXISTS, GETTING_QUIZ_ERROR, DELETE_QUIZ_ERROR, UPDATE_QUIZ_ERROR, MOVING_QUIZ_ERROR, DUPLICATE_QUIZ_ERROR, COPY_QUIZ_ERROR } = require('../constants/errorCodes');
class QuizController {
async create(req, res, next) {
constructor(quizModel, foldersModel) {
this.folders = foldersModel;
console.log("QuizController constructor: folders", this.folders);
this.quizzes = quizModel;
console.log("QuizController constructor: quizzes", this.quizzes);
}
create = async (req, res, next) => {
try {
const { title, content, folderId } = req.body;
@ -16,13 +24,13 @@ class QuizController {
}
// Is this folder mine
const owner = await folderModel.getOwner(folderId);
const owner = await this.folders.getOwner(folderId);
if (owner != req.user.userId) {
throw new AppError(FOLDER_NOT_FOUND);
}
const result = await model.create(title, content, folderId, req.user.userId);
const result = await this.quizzes.create(title, content, folderId, req.user.userId);
if (!result) {
throw new AppError(QUIZ_ALREADY_EXISTS);
@ -32,13 +40,12 @@ class QuizController {
message: 'Quiz créé avec succès.'
});
}
catch (error) {
} catch (error) {
return next(error);
}
}
};
async get(req, res, next) {
get = async (req, res, next) => {
try {
const { quizId } = req.params;
@ -46,8 +53,7 @@ class QuizController {
throw new AppError(MISSING_REQUIRED_PARAMETER);
}
const content = await model.getContent(quizId);
const content = await this.quizzes.getContent(quizId);
if (!content) {
throw new AppError(GETTING_QUIZ_ERROR);
@ -62,13 +68,12 @@ class QuizController {
data: content
});
}
catch (error) {
} catch (error) {
return next(error);
}
}
};
async delete(req, res, next) {
delete = async (req, res, next) => {
try {
const { quizId } = req.params;
@ -77,13 +82,13 @@ class QuizController {
}
// Is this quiz mine
const owner = await model.getOwner(quizId);
const owner = await this.quizzes.getOwner(quizId);
if (owner != req.user.userId) {
throw new AppError(QUIZ_NOT_FOUND);
}
const result = await model.delete(quizId);
const result = await this.quizzes.delete(quizId);
if (!result) {
throw new AppError(DELETE_QUIZ_ERROR);
@ -93,13 +98,12 @@ class QuizController {
message: 'Quiz supprimé avec succès.'
});
}
catch (error) {
} catch (error) {
return next(error);
}
}
};
async update(req, res, next) {
update = async (req, res, next) => {
try {
const { quizId, newTitle, newContent } = req.body;
@ -108,13 +112,13 @@ class QuizController {
}
// Is this quiz mine
const owner = await model.getOwner(quizId);
const owner = await this.quizzes.getOwner(quizId);
if (owner != req.user.userId) {
throw new AppError(QUIZ_NOT_FOUND);
}
const result = await model.update(quizId, newTitle, newContent);
const result = await this.quizzes.update(quizId, newTitle, newContent);
if (!result) {
throw new AppError(UPDATE_QUIZ_ERROR);
@ -124,13 +128,12 @@ class QuizController {
message: 'Quiz mis à jours avec succès.'
});
}
catch (error) {
} catch (error) {
return next(error);
}
}
};
async move(req, res, next) {
move = async (req, res, next) => {
try {
const { quizId, newFolderId } = req.body;
@ -139,20 +142,20 @@ class QuizController {
}
// Is this quiz mine
const quizOwner = await model.getOwner(quizId);
const quizOwner = await this.quizzes.getOwner(quizId);
if (quizOwner != req.user.userId) {
throw new AppError(QUIZ_NOT_FOUND);
}
// Is this folder mine
const folderOwner = await folderModel.getOwner(newFolderId);
const folderOwner = await this.folders.getOwner(newFolderId);
if (folderOwner != req.user.userId) {
throw new AppError(FOLDER_NOT_FOUND);
}
const result = await model.move(quizId, newFolderId);
const result = await this.quizzes.move(quizId, newFolderId);
if (!result) {
throw new AppError(MOVING_QUIZ_ERROR);
@ -162,15 +165,12 @@ class QuizController {
message: 'Utilisateur déplacé avec succès.'
});
}
catch (error) {
} catch (error) {
return next(error);
}
};
}
async copy(req, res, next) {
copy = async (req, res, next) => {
const { quizId, newTitle, folderId } = req.body;
if (!quizId || !newTitle || !folderId) {
@ -201,9 +201,9 @@ class QuizController {
// }
// res.status(500).json(Response.serverError(error.message));
// }
}
};
async deleteQuizzesByFolderId(req, res, next) {
deleteQuizzesByFolderId = async (req, res, next) => {
try {
const { folderId } = req.body;
@ -220,29 +220,29 @@ class QuizController {
} catch (error) {
return next(error);
}
}
};
async duplicate(req, res, next) {
duplicate = async (req, res, next) => {
const { quizId } = req.body;
try {
const newQuizId = await model.duplicate(quizId,req.user.userId);
const newQuizId = await this.quizzes.duplicate(quizId, req.user.userId);
res.status(200).json({ success: true, newQuizId });
} catch (error) {
return next(error);
}
}
};
async quizExists(title, userId) {
quizExists = async (title, userId) => {
try {
const existingFile = await model.quizExists(title, userId);
const existingFile = await this.quizzes.quizExists(title, userId);
return existingFile !== null;
} catch (error) {
throw new AppError(GETTING_QUIZ_ERROR);
}
}
};
async Share(req, res, next) {
share = async (req, res, next) => {
try {
const { quizId, email } = req.body;
@ -258,13 +258,12 @@ class QuizController {
message: 'Quiz partagé avec succès.'
});
}
catch (error) {
} catch (error) {
return next(error);
}
}
};
async getShare(req, res, next) {
getShare = async (req, res, next) => {
try {
const { quizId } = req.params;
@ -272,7 +271,7 @@ class QuizController {
throw new AppError(MISSING_REQUIRED_PARAMETER);
}
const content = await model.getContent(quizId);
const content = await this.quizzes.getContent(quizId);
if (!content) {
throw new AppError(GETTING_QUIZ_ERROR);
@ -282,13 +281,12 @@ class QuizController {
data: content.title
});
}
catch (error) {
} catch (error) {
return next(error);
}
}
};
async receiveShare(req, res, next) {
receiveShare = async (req, res, next) => {
try {
const { quizId, folderId } = req.body;
@ -296,17 +294,17 @@ class QuizController {
throw new AppError(MISSING_REQUIRED_PARAMETER);
}
const folderOwner = await folderModel.getOwner(folderId);
const folderOwner = await this.folders.getOwner(folderId);
if (folderOwner != req.user.userId) {
throw new AppError(FOLDER_NOT_FOUND);
}
const content = await model.getContent(quizId);
const content = await this.quizzes.getContent(quizId);
if (!content) {
throw new AppError(GETTING_QUIZ_ERROR);
}
const result = await model.create(content.title, content.content, folderId, req.user.userId);
const result = await this.quizzes.create(content.title, content.content, folderId, req.user.userId);
if (!result) {
throw new AppError(QUIZ_ALREADY_EXISTS);
}
@ -314,13 +312,11 @@ class QuizController {
return res.status(200).json({
message: 'Quiz partagé reçu.'
});
}
catch (error) {
} catch (error) {
return next(error);
}
}
};
}
module.exports = new QuizController;
module.exports = QuizController;

View file

@ -1,7 +1,5 @@
const emailer = require('../config/email.js');
const userModel = require('../models/users.js');
const jwt = require('../middleware/jwtToken.js');
const db = require('../config/db.js');
const AppError = require('../middleware/AppError.js');
const { MISSING_REQUIRED_PARAMETER, LOGIN_CREDENTIALS_ERROR, GENERATE_PASSWORD_ERROR, UPDATE_PASSWORD_ERROR, DELETE_USER_ERROR } = require('../constants/errorCodes');
@ -9,10 +7,8 @@ const { MISSING_REQUIRED_PARAMETER, LOGIN_CREDENTIALS_ERROR, GENERATE_PASSWORD_E
// controllers must use arrow functions to bind 'this' to the class instance in order to access class properties as callbacks in Express
class UsersController {
constructor() {
console.log("UsersController constructor: db", db)
this.db = db;
this.users = new userModel(this.db);
constructor(userModel) {
this.users = userModel;
console.log("UsersController constructor: users", this.users);
}

View file

@ -1,11 +1,12 @@
//model
// const db = require('../config/db.js')
const ObjectId = require('mongodb').ObjectId;
const Quiz = require('./quiz.js');
// need to access the Quiz model from the Folders model
class Folders {
constructor(db) {
constructor(db, quizModel) {
this.db = db;
this.quizModel = quizModel;
}
async create(title, userId) {

View file

@ -1,8 +1,12 @@
const db = require('../config/db.js')
//const db = require('../config/db.js')
const { ObjectId } = require('mongodb');
class Images {
constructor(db) {
this.db = db;
}
async upload(file, userId) {
await db.connect()
const conn = db.getConnection();
@ -41,4 +45,4 @@ class Images {
}
module.exports = new Images;
module.exports = Images;

View file

@ -1,11 +1,15 @@
const db = require('../config/db.js')
const { ObjectId } = require('mongodb');
class Quiz {
constructor(db) {
console.log("Quiz constructor: db", db)
this.db = db;
}
async create(title, content, folderId, userId) {
await db.connect()
const conn = db.getConnection();
await this.db.connect()
const conn = this.db.getConnection();
const quizCollection = conn.collection('files');
@ -28,8 +32,8 @@ class Quiz {
}
async getOwner(quizId) {
await db.connect()
const conn = db.getConnection();
await this.db.connect()
const conn = this.db.getConnection();
const quizCollection = conn.collection('files');
@ -39,8 +43,8 @@ class Quiz {
}
async getContent(quizId) {
await db.connect()
const conn = db.getConnection();
await this.db.connect()
const conn = this.db.getConnection();
const quizCollection = conn.collection('files');
@ -50,8 +54,8 @@ class Quiz {
}
async delete(quizId) {
await db.connect()
const conn = db.getConnection();
await this.db.connect()
const conn = this.db.getConnection();
const quizCollection = conn.collection('files');
@ -62,8 +66,8 @@ class Quiz {
return true;
}
async deleteQuizzesByFolderId(folderId) {
await db.connect();
const conn = db.getConnection();
await this.db.connect();
const conn = this.db.getConnection();
const quizzesCollection = conn.collection('files');
@ -72,8 +76,8 @@ class Quiz {
}
async update(quizId, newTitle, newContent) {
await db.connect()
const conn = db.getConnection();
await this.db.connect()
const conn = this.db.getConnection();
const quizCollection = conn.collection('files');
@ -85,8 +89,8 @@ class Quiz {
}
async move(quizId, newFolderId) {
await db.connect()
const conn = db.getConnection();
await this.db.connect()
const conn = this.db.getConnection();
const quizCollection = conn.collection('files');
@ -119,8 +123,8 @@ class Quiz {
}
async quizExists(title, userId) {
await db.connect();
const conn = db.getConnection();
await this.db.connect();
const conn = this.db.getConnection();
const filesCollection = conn.collection('files');
const existingFolder = await filesCollection.findOne({ title: title, userId: userId });
@ -130,4 +134,4 @@ class Quiz {
}
module.exports = new Quiz;
module.exports = Quiz;

View file

@ -1,5 +1,4 @@
//user
// const db = require('../config/db.js');
const bcrypt = require('bcrypt');
const AppError = require('../middleware/AppError.js');
const { USER_ALREADY_EXISTS } = require('../constants/errorCodes');

View file

@ -1,18 +1,22 @@
const express = require('express');
const router = express.Router();
const jwt = require('../middleware/jwtToken.js');
const folders = require('../app.js').folders;
const foldersController = require('../controllers/folders.js')
router.post("/create", jwt.authenticate, foldersController.create);
router.get("/getUserFolders", jwt.authenticate, foldersController.getUserFolders);
router.get("/getFolderContent/:folderId", jwt.authenticate, foldersController.getFolderContent);
router.delete("/delete/:folderId", jwt.authenticate, foldersController.delete);
router.put("/rename", jwt.authenticate, foldersController.rename);
router.post("/create", jwt.authenticate, folders.create);
router.get("/getUserFolders", jwt.authenticate, folders.getUserFolders);
router.get("/getFolderContent/:folderId", jwt.authenticate, folders.getFolderContent);
router.delete("/delete/:folderId", jwt.authenticate, folders.delete);
router.put("/rename", jwt.authenticate, folders.rename);
//router.post("/duplicate", jwt.authenticate, foldersController.duplicate);
router.post("/duplicate", jwt.authenticate, foldersController.duplicate);
router.post("/duplicate", jwt.authenticate, folders.duplicate);
router.post("/copy/:folderId", jwt.authenticate, foldersController.copy);
router.post("/copy/:folderId", jwt.authenticate, folders.copy);
module.exports = router;
// export also folders (the controller)
module.exports.folders = folders;
// Refer to folders using: const folders = require('../controllers/folders.js').folders;

View file

@ -1,15 +1,15 @@
const express = require('express');
const router = express.Router();
const images = require('../app.js').images;
const jwt = require('../middleware/jwtToken.js');
const imagesController = require('../controllers/images.js')
// For getting the image out of the form data
const multer = require('multer');
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
router.post("/upload", jwt.authenticate, upload.single('image'), imagesController.upload);
router.get("/get/:id", imagesController.get);
router.post("/upload", jwt.authenticate, upload.single('image'), images.upload);
router.get("/get/:id", images.get);
module.exports = router;

View file

@ -1,19 +1,22 @@
const express = require('express');
const router = express.Router();
const quizzes = require('../app.js').quizzes;
const jwt = require('../middleware/jwtToken.js');
const quizController = require('../controllers/quiz.js')
router.post("/create", jwt.authenticate, quizController.create);
router.get("/get/:quizId", jwt.authenticate, quizController.get);
router.delete("/delete/:quizId", jwt.authenticate, quizController.delete);
router.put("/update", jwt.authenticate, quizController.update);
router.put("/move", jwt.authenticate, quizController.move);
if (!quizzes) {
console.error("quizzes is not defined");
}
router.post("/duplicate", jwt.authenticate, quizController.duplicate);
router.post("/copy/:quizId", jwt.authenticate, quizController.copy);
router.put("/Share", jwt.authenticate, quizController.Share);
router.get("/getShare/:quizId", jwt.authenticate, quizController.getShare);
router.post("/receiveShare", jwt.authenticate, quizController.receiveShare);
router.post("/create", jwt.authenticate, quizzes.create);
router.get("/get/:quizId", jwt.authenticate, quizzes.get);
router.delete("/delete/:quizId", jwt.authenticate, quizzes.delete);
router.put("/update", jwt.authenticate, quizzes.update);
router.put("/move", jwt.authenticate, quizzes.move);
router.post("/duplicate", jwt.authenticate, quizzes.duplicate);
router.post("/copy/:quizId", jwt.authenticate, quizzes.copy);
router.put("/Share", jwt.authenticate, quizzes.share);
router.get("/getShare/:quizId", jwt.authenticate, quizzes.getShare);
router.post("/receiveShare", jwt.authenticate, quizzes.receiveShare);
module.exports = router;

View file

@ -1,10 +1,7 @@
const express = require('express');
const router = express.Router();
const users = require('../app.js').users;
const jwt = require('../middleware/jwtToken.js');
const usersController = require('../controllers/users.js');
// instantiate the controller
const users = new usersController();
router.post("/register", users.register);
router.post("/login", users.login);