Skip to content

Commit

Permalink
Ajout de l'upload de photogallery pour event et changement de facon d…
Browse files Browse the repository at this point in the history
…'upload considérant qu'on a 2 champ possible maintenant
  • Loading branch information
SonofaPancak committed Sep 6, 2023
1 parent 158a34e commit 4bdaaf9
Show file tree
Hide file tree
Showing 7 changed files with 65 additions and 52 deletions.
8 changes: 8 additions & 0 deletions src/Events/Models/Event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,10 @@ class Event extends AbstractModel {
type: [mongoose.Types.ObjectId],
ref: "Place"
},
photoGallery:{
type: mongoose.Types.ObjectId,
ref: "Media"
},
status: {
type: Status.schema
}
Expand Down Expand Up @@ -209,6 +213,7 @@ class Event extends AbstractModel {
schedule: document.schedule ?? [],
subEvents: document.subEvents ?? [],
location: document.location ?? [],
photoGallery: document.photoGallery ?? '',
status: document.status ?? '',
type: document.type ?? '',
createdAt: document.createdAt ?? '',
Expand Down Expand Up @@ -237,6 +242,7 @@ class Event extends AbstractModel {
middlewarePopulateProperty(this, 'subEvents');
middlewarePopulateProperty(this, 'eventType');
middlewarePopulateProperty(this, 'location');
middlewarePopulateProperty(this, 'photoGallery');

populateUser(this, "status.requestedBy", User.getInstance().mongooseModel);
populateUser(this, "status.lastModifiedBy", User.getInstance().mongooseModel);
Expand All @@ -254,6 +260,8 @@ class Event extends AbstractModel {
middlewarePopulateProperty(this, 'subEvents');
middlewarePopulateProperty(this, 'eventType');
middlewarePopulateProperty(this, 'location');
middlewarePopulateProperty(this, 'photoGallery');


populateUser(this, "status.requestedBy", User.getInstance().mongooseModel);
populateUser(this, "status.lastModifiedBy", User.getInstance().mongooseModel);
Expand Down
1 change: 1 addition & 0 deletions src/Events/Schemas/EventSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,6 @@ export interface EventSchema extends Document {
schedule:[Schedule]
subEvents:[ObjectId]
location:[ObjectId]
photoGallery:ObjectId
status:Status
}
35 changes: 14 additions & 21 deletions src/Media/Controllers/MediasController.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import AbstractController from "../../Abstract/Controller";
import MediasService from "../Services/MediasService";
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";
Expand Down Expand Up @@ -42,14 +40,6 @@ class MediasController extends AbstractController { //implements ControllerContr
return MediasController._instance;
}

public basepath(requestData:any) {
return SuccessResponse.create({"basepath":"truetrue"}, StatusCodes.OK, "asdasdasd");
}

public uploadSingle(requestData:any) {
return SuccessResponse.create({"uploadSingle":"truetrue"}, StatusCodes.OK, "Uploading single media comming into dev!");
}

public internalCreateFromRecord(record:Record){
if(record.isValid()){
const createData = {
Expand All @@ -62,6 +52,7 @@ class MediasController extends AbstractController { //implements ControllerContr
fileType: record.fileType,
fileName: record.filenameNoExt,
extension: record.extension,
mediaField: record.mediaField,
entityId: record.entityId ?? '',
entityType: record.entityType ?? '',
uploadedBy: record.userId,
Expand Down Expand Up @@ -91,17 +82,19 @@ class MediasController extends AbstractController { //implements ControllerContr
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))
//Create keys (modelName) and values (accepted media field) for each model
const entities:any = {
[Person.getInstance().modelName]: ["mainImage"],
[Organisation.getInstance().modelName]: ["mainImage"],
[Project.getInstance().modelName]: ["mainImage"],
[Event.getInstance().modelName]: ["mainImage", "photoGallery"],
[Place.getInstance().modelName]: ["mainImage"]
};
//For all keys (modelName) check if image is accepted
if(!Object.keys(entities).includes(requestData.entityType))
return false;
//Check mediaField
if(requestData.mediaField !== "mainImage")
//For all values, check if mediaField is accepted for that model
if(!entities[requestData.entityType].includes(requestData.mediaField))
return false
return true
}
Expand Down Expand Up @@ -138,7 +131,7 @@ class MediasController extends AbstractController { //implements ControllerContr
}

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

if (linkingMediaResponse.error){
Expand Down
5 changes: 5 additions & 0 deletions src/Media/Models/Media.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@ class Media extends AbstractModel {
type: String,
enum: fileExtensionList
},
mediaField: {
type: String,
enum: ["mainImage", "photoGallery"]
},
slug: {
type: String,
slug: ["entityId"],
Expand Down Expand Up @@ -160,6 +164,7 @@ class Media extends AbstractModel {
fileType: document.fileType ?? '',
fileName: document.fileName ?? '',
extension: document.extension ?? '',
mediaField: document.mediaField ?? '',
slug: document.slug ?? '',
entityId: document.entityId ?? '',
entityType: document.entityType ?? '',
Expand Down
47 changes: 25 additions & 22 deletions src/Media/Record/Record.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export default class Record {
public entityId:string;
public extension:string;
public userId:string; //media -> uploadedBy
public mediaField;

//Media info
public title:string;
Expand All @@ -37,11 +38,13 @@ export default class Record {
public file_buffer:any;


constructor(req:any, res:any, entityId:string, mediaField:string, entityType:string){
constructor(data:any, files:any, userId:any, entityId:string, mediaField:string, entityType:string){

this.userId = req.user._id;
const file = files[mediaField][0];
this.userId = userId;
this.mediaField = mediaField;

const tryExt:string|false = mime.extension(req.file.mimetype);
const tryExt:string|false = mime.extension(file.mimetype);
this.extension = (tryExt !== false ? tryExt : "");

if(this.extension !== ""){
Expand All @@ -50,7 +53,7 @@ export default class Record {
mediaField,
this.userId,
FileStorage.getUniquePrefix(),
FileStorage.removeExtension(req.file.originalname)
FileStorage.removeExtension(file.originalname)
],
this.extension
)
Expand All @@ -62,7 +65,7 @@ export default class Record {
mediaField,
this.userId,
FileStorage.getUniquePrefix(),
req.file.originalname
file.originalname
],
"");
this.filenameAndExt = this.filenameNoExt;
Expand All @@ -75,25 +78,25 @@ export default class Record {
this.url = "/medias/"+ this.entityType + "/" + this.entityId + "/" + this.filenameAndExt;

//Media info
if(req.body.data !== undefined){
this.title = req.body.data.title
this.alt = req.body.data.alt
this.description = req.body.data.description
this.licence = req.body.data.licence
this.fileType = req.body.data.fileType
if(data !== undefined){
this.title = data.title
this.alt = data.alt
this.description = data.description
this.licence = data.licence
this.fileType = data.fileType
}

//Multer file props
if(req.file !== undefined){
this.file_fieldName = req.file.fieldName
this.file_originalname = req.file.originalname
this.file_encoding = req.file.encoding
this.file_mimetype = req.file.mimetype
this.file_size = req.file.size
this.file_destination = req.file.destination
this.file_filename = req.file.filename
this.file_path = req.file.path
this.file_buffer = req.file.buffer
//Multer file props (transformed req.files)
if(file !== undefined){
this.file_fieldName = file.fieldName
this.file_originalname = file.originalname
this.file_encoding = file.encoding
this.file_mimetype = file.mimetype
this.file_size = file.size
this.file_destination = file.destination
this.file_filename = file.filename
this.file_path = file.path
this.file_buffer = file.buffer
}
}

Expand Down
20 changes: 11 additions & 9 deletions src/Media/Routes/MediasRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,11 @@ import multer from "multer";
import {ErrorResponse} from "@src/Http/Responses/ErrorResponse";
import PublicStorage from "@src/Storage/Files/PublicStorage";
import * as path from "path";
import Organisation from "@src/Organisations/Models/Organisation";
import Person from "@src/Persons/Models/Person";
import {now} from "@src/Helpers/DateTime";
import {objectIdSanitizerAlias} from "@src/Security/SanitizerAliases/ObjectIdSanitizerAlias";
import {noHtmlStringSanitizerAlias} from "@src/Security/SanitizerAliases/NoHtmlStringSanitizerAlias";
import {isInEnumSanitizerAlias} from "@src/Security/SanitizerAliases/IsInEnumSanitizerAlias";
import {EntityTypesEnum} from "@src/Entities/EntityTypes";
import Project from "@src/Projects/Models/Project";
import Event from "@src/Events/Models/Event";
import Place from "@src/Places/Models/Place";


class MediasRoutes extends AbstractRoute {
Expand Down Expand Up @@ -117,15 +112,21 @@ class MediasRoutes extends AbstractRoute {
});

this.routerInstanceAuthentification.post('/upload', [
multipartMiddlewareTemporaryHandler.single("mainImage"),
multipartMiddlewareTemporaryHandler.fields([
{ name: 'mainImage', maxCount: 1 },
{ name: 'photoGallery', maxCount: 1 }
]),
this.contentTypeParser.bind(this),
...this.addMiddlewares("all"),
this.createOrUpdateDispatch.bind(this),
this.routeSendResponse.bind(this),
]);

this.routerInstanceAuthentification.post('/update', [
multipartMiddlewareTemporaryHandler.single("mainImage"),
multipartMiddlewareTemporaryHandler.fields([
{ name: 'mainImage', maxCount: 1 },
{ name: 'photoGallery', maxCount: 1 }
]),
this.contentTypeParser.bind(this),
...this.addMiddlewares("all"),
this.createOrUpdateDispatch.bind(this),
Expand Down Expand Up @@ -154,8 +155,9 @@ class MediasRoutes extends AbstractRoute {

public async createOrUpdateDispatch(req: Request, res: Response, next: NextFunction): Promise<any> {

console.log("file", req.file, "\n\n", "files", req.files)
//If file attached (either upload or update)
if(req.file !== undefined){
if(req.files !== undefined){
await this.createAndReplaceHandler(req, res);
}
//if no file attached
Expand Down Expand Up @@ -201,7 +203,7 @@ class MediasRoutes extends AbstractRoute {
const entityResponse = await EntityControllerFactory.getControllerFromEntity(entityType).search( { id : entityId } );
const oldMediaId = entityResponse?.data?.[mediaField]?._id;

const record = new Record(req, res, entityId, mediaField, entityType);
const record = new Record(req.body.data, req.files, req.user._id, 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;
Expand Down
1 change: 1 addition & 0 deletions src/Media/Schemas/MediaSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export interface MediaSchema extends Document {
fileType: string;
fileName: string;
extension: string;
mediaField: string;
slug: string;
entityId: mongoose.ObjectId;
entityType: string;
Expand Down

0 comments on commit 4bdaaf9

Please sign in to comment.