-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUploadController.js
51 lines (42 loc) · 1.23 KB
/
UploadController.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
const fs = require('fs');
const { resolve } = require('path');
const Image = require('../models/Image');
module.exports = {
async index(req, res) {
const images = await Image.find().sort();
return res.json(images);
},
async store(req, res) {
try {
const { filename, size, location } = req.file;
const URLs = {
local: `http://${process.env.HOST}:${process.env.PORT}/files/${filename}`,
aws_s3: location,
};
const url = URLs[process.env.STORAGE_TYPE];
const image = await Image.create({
name: filename,
size,
url,
});
return res.status(201).json(image);
} catch (err) {
return res.status(422).json({ error: 'Could not upload the image.' });
}
},
async destroy(req, res) {
try {
const { id } = req.params;
const image = await Image.findById(id);
if (!image) {
return res.status(404).json({ error: 'File not found.' });
}
const filePath = resolve('tmp', 'uploads', image.name);
await fs.promises.unlink(filePath);
await image.deleteOne();
return res.sendStatus(204);
} catch (err) {
return res.status(422).json({ error: 'Could not delete the image.' });
}
},
};