Skip to content

Commit

Permalink
Refactor de MediaRoutes en prévision d'ajouter de nouveaux champs pou…
Browse files Browse the repository at this point in the history
…r media
  • Loading branch information
SonofaPancak committed Sep 2, 2023
1 parent 56134ba commit 158a34e
Show file tree
Hide file tree
Showing 2 changed files with 132 additions and 95 deletions.
97 changes: 93 additions & 4 deletions src/Media/Controllers/MediasController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@ import Media from "../Models/Media";
import {SuccessResponse} from "../../Http/Responses/SuccessResponse";
import {StatusCodes} from "http-status-codes";
import Record from "../Record/Record";
import { Request, Response } from "express";
import FileStorage from "@src/Storage/Files/FileStorage";
import LogHelper from "@src/Monitoring/Helpers/LogHelper";
import Person from "@src/Persons/Models/Person";
import Organisation from "@src/Organisations/Models/Organisation";
import Project from "@src/Projects/Models/Project";
import Place from "@src/Places/Models/Place";
import Event from "@src/Events/Models/Event";
import EntityControllerFactory from "@src/Abstract/EntityControllerFactory";

class MediasController extends AbstractController { //implements ControllerContract {

Expand Down Expand Up @@ -69,13 +78,93 @@ class MediasController extends AbstractController { //implements ControllerContr
return {error:true, data:{}};
}

public internalUpdateToArchived(toArchiveId:any){
return this.service.update({ _id : toArchiveId, dbStatus:"archived"});
}

public internalDelete(entityId:any, filenameNoExt:string):any {
return this.service.findAndDelete({ entityId: entityId, fileName: filenameNoExt });
}

public checkRequestData(req:Request):boolean{
const requestData = req.body.data;

//Check if data contains entityId, mediaField and entityType
if(requestData.entityId == undefined ||
requestData.mediaField === undefined ||
requestData.entityType === undefined) {
return false;
}
//Check entityType
const entities:any = [
Person.getInstance().modelName,
Organisation.getInstance().modelName,
Project.getInstance().modelName,
Event.getInstance().modelName,
Place.getInstance().modelName];
if( !entities.includes(requestData.entityType))
return false;
//Check mediaField
if(requestData.mediaField !== "mainImage")
return false
return true
}

public async saveFile(res: Response, record:Record):Promise<boolean>{
//Save file
await FileStorage.saveFile(record).then(function() {
LogHelper.log("Saved file");
}).catch(function (){
LogHelper.log("It catched that the saveFile didn't work!");
res.serviceResponse.multer.error = true;
res.serviceResponse.multer.message = "Couldn't save file to the server :( , saving file failed"
return false;
});
return true
}

//Insert media and delete file if failed
public async insertMedia(res:Response, record:Record){
const mediaResponse = await this.internalCreateFromRecord(record);
res.serviceResponse = mediaResponse;
if (mediaResponse.error){
res.serviceResponse.failMessage = "Couldn't save file, creating media failed"

//Delete file
FileStorage.deleteFile(record);

res.serviceResponse.multer = {};
res.serviceResponse.multer.error = true;
res.serviceResponse.multer.message = "Deleted file";
return false;
}
return mediaResponse.data._id
}

public async linkEntityToMedia(res:Response, record:Record, toLinkMediaId:any){
const updateRequest = { id: record.entityId, mainImage : toLinkMediaId };
const linkingMediaResponse = await EntityControllerFactory.getControllerFromEntity(record.entityType).update(updateRequest);

if (linkingMediaResponse.error){
//Delete media
res.serviceResponse = await this.internalDelete(record.entityId, record.filenameNoExt);
res.serviceResponse.failMessage = "Couldn't save file, failed to link media to entity";
//Delete file
FileStorage.deleteFile(record);

res.serviceResponse.multer = {};
res.serviceResponse.multer.error = true;
res.serviceResponse.multer.message = "Deleted file";
return false;
}
return true;
}

public async archiveOldMedia(res:Response, toArchiveId:any){
res.serviceResponse.oldMedia = await this.service.update({ _id : toArchiveId, dbStatus:"archived"});
if (!res.serviceResponse.oldMedia.error)
res.serviceResponse.oldMedia.message = "old media status set to archived successfully"
else
res.serviceResponse.oldMedia.message = "old media status update to archived failed"
}


}

export default MediasController;
130 changes: 39 additions & 91 deletions src/Media/Routes/MediasRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,103 +186,51 @@ class MediasRoutes extends AbstractRoute {
}*/

//Check if entityId, mediaField, entityType is in the request;
const requestData = req.body.data;
const { entityId, mediaField, entityType } = requestData;


if(requestData.entityId == undefined ||
requestData.mediaField === undefined ||
requestData.entityType === undefined) {
//Insert message missing field here
res.serviceResponse = ErrorResponse.create(new Error, StatusCodes.BAD_REQUEST,
"Required field : entityId : (the entityId of the entity media belongs to), "+
"mediaField : ('mainImage', ...), "+
"entityType: (type of entity 'Person', 'Organisation' ...)");
return;
const isReqDataCorrect = this.controllerInstance.checkRequestData(req);
if(!isReqDataCorrect){
//Insert message missing field here
res.serviceResponse = ErrorResponse.create(new Error, StatusCodes.BAD_REQUEST,
"Required field : entityId : (the entityId of the entity media belongs to), "+
"mediaField : ('mainImage', ...), "+
"entityType: (type of entity 'Person', 'Organisation' ...)");
return;
}

//if entity have media field
//TODO : Need to make a check for this (this goes with making the create check for multiple field multer.single ("mainImage, and others..."))
//Temporary check (entityType is person or org and mediaField is mainImage)
const entities:any = [
Person.getInstance().modelName,
Organisation.getInstance().modelName,
Project.getInstance().modelName,
Event.getInstance().modelName,
Place.getInstance().modelName];
if( entities.includes(entityType)
&& mediaField == "mainImage" ) {

//Get old media ID if exist
const entityResponse = await EntityControllerFactory.getControllerFromEntity(entityType).search( { id : entityId } );
const oldMediaId = entityResponse?.data?.[mediaField]?._id;

const record = new Record(req, res, entityId, mediaField, entityType);
if (!record.isValid()){
res.serviceResponse = ErrorResponse.create(new Error, StatusCodes.BAD_REQUEST, "Couldn't create Record associated with the file that was sent" );
return;
}

//Save file
await FileStorage.saveFile(record).then(function() {
LogHelper.log("Saved file");
}).catch(function (){
LogHelper.log("It catched that the saveFile didn't work!");
res.serviceResponse.multer.error = true;
res.serviceResponse.multer.message = "Couldn't save file to the server :( , saving file failed"
return;
});

const mediasController = MediasController.getInstance();
//insert a new object media inside the database with all the information required
const mediaResponse = await mediasController.internalCreateFromRecord(record);
res.serviceResponse = mediaResponse;
if (mediaResponse.error){
res.serviceResponse.failMessage = "Couldn't save file, creating media failed"

//Delete file
FileStorage.deleteFile(record);

res.serviceResponse.multer = {};
res.serviceResponse.multer.error = true;
res.serviceResponse.multer.message = "Deleted file";
return;
}

const toLinkMediaId = mediaResponse.data._id;
const updateRequest = { id: entityId, mainImage : toLinkMediaId };
const linkingMediaResponse = await EntityControllerFactory.getControllerFromEntity(entityType).update(updateRequest);

if (linkingMediaResponse.error){
//Delete media
res.serviceResponse = await mediasController.internalDelete(record.entityId, record.filenameNoExt);
res.serviceResponse.failMessage = "Couldn't save file, failed to link media to entity";
//Delete file
FileStorage.deleteFile(record);

res.serviceResponse.multer = {};
res.serviceResponse.multer.error = true;
res.serviceResponse.multer.message = "Deleted file";
return;
}
const {entityId, mediaField, entityType} = req.body.data;
//Get old media ID if exist
const entityResponse = await EntityControllerFactory.getControllerFromEntity(entityType).search( { id : entityId } );
const oldMediaId = entityResponse?.data?.[mediaField]?._id;

const record = new Record(req, res, entityId, mediaField, entityType);
if (!record.isValid()){
res.serviceResponse = ErrorResponse.create(new Error, StatusCodes.BAD_REQUEST, "Couldn't create Record associated with the file that was sent" );
return;
}

//Save file
const isFileSaved = await this.controllerInstance.saveFile(res, record);
if(!isFileSaved)
return;

//If entity had old media then update it
if (oldMediaId !== undefined){
res.serviceResponse.oldMedia = await this.controllerInstance.update( { id: oldMediaId, dbStatus: "archived" });
if (!res.serviceResponse.oldMedia.error)
res.serviceResponse.oldMedia.message = "old media status set to archived successfully"
else
res.serviceResponse.oldMedia.message = "old media status update to archived failed"
}
//Insert new media object in db and handle error (delete file if fail)
const toLinkMediaId = await this.controllerInstance.insertMedia(res, record);
//toLinkMediaId is false if failed
if(toLinkMediaId == false)
return;

//Everything succeeded
res.serviceResponse.message = "Success to save file, create media, and link media to entity!";
res.serviceResponse.action = "create";
const userHistoryCreated: boolean = await this.controllerInstance.createUserHistory(req, res);
const isLinkedSuccess = await this.controllerInstance.linkEntityToMedia(res, record, toLinkMediaId)
if(!isLinkedSuccess)
return;

//If entity had old media then update it
if (oldMediaId !== undefined){
await this.controllerInstance.archiveOldMedia(res, oldMediaId)
}
//Return msg no field to put image into entity
res.serviceResponse = ErrorResponse.create(new Error, StatusCodes.BAD_REQUEST, "Entity upload is désactivated or invalid field for upload.");

//Everything succeeded
res.serviceResponse.message = "Success to save file, create media, and link media to entity!";
res.serviceResponse.action = "create";
const userHistoryCreated: boolean = await this.controllerInstance.createUserHistory(req, res);
return;
}

Expand Down

0 comments on commit 158a34e

Please sign in to comment.