-
Notifications
You must be signed in to change notification settings - Fork 1
/
photoController.js
142 lines (101 loc) · 2.88 KB
/
photoController.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import Photo from "../models/photoModel.js";
import { v2 as cloudinary } from 'cloudinary';
import fs from "fs";
const createPhoto = async (req,res) => {
const result = await cloudinary.uploader.upload(
req.files.image.tempFilePath,
{
use_filename: true,
folder : 'EBAG_TR',
}
);
try {
await Photo.create({
name:req.body.name,
description: req.body.description,
user:res.locals.user._id,
url: result.secure_url,
image_id: result.public_id,
});
fs.unlinkSync(req.files.image.tempFilePath);
res.status(201).redirect("/users/dashboard")
} catch (error) {
res.status(500).json({
succeded: false,
error,
});
}
};
const getAllPhotos = async (req,res) => {
try {
const photos = res.locals.user ? await Photo.find({user: {$ne: res.locals.user._id}})
:
await Photo.find({});
res.status(200).render("photos",{
photos,
link: 'photos',
});
} catch (error) {
res.status(500).json({
succeded: false,
error,
});
}
};
const getAPhoto = async (req,res) => {
try {
const photo = await Photo.findById({_id : req.params.id}).populate('user');
res.status(200).render("photo",{
photo,
link: 'photos',
});
} catch (error) {
res.status(500).json({
succeded: false,
error,
});
}
}
const deletePhoto = async (req,res) => {
try {
const photo = await Photo.findById(req.params.id);
const photoId = photo.image_id;
await cloudinary.uploader.destroy(photoId);
await Photo.findOneAndRemove({_id : req.params.id});
res.status(200).redirect('/users/dashboard');
} catch (error) {
res.status(500).json({
succeded: false,
error,
});
}
}
const updatePhoto = async (req,res) => {
try {
const photo = await Photo.findById(req.params.id);
if(req.files){
const photoId = photo.image_id;
await cloudinary.uploader.destroy(photoId);
const result = await cloudinary.uploader.upload(
req.files.image.tempFilePath,
{
use_filename: true,
folder : 'EBAG_TR',
}
);
photo.url = result.secure_url;
photo.image_id = result.public_id;
fs.unlinkSync(req.files.image.tempFilePath);
}
photo.name = req.body.name;
photo.description = req.body.description;
photo.save();
res.status(200).redirect(`/photos/${req.params.id}`);
} catch (error) {
res.status(500).json({
succeded: false,
error,
});
}
}
export {createPhoto, getAllPhotos, getAPhoto,deletePhoto,updatePhoto};