-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathdeleteProject.js
More file actions
77 lines (67 loc) · 1.98 KB
/
Copy pathdeleteProject.js
File metadata and controls
77 lines (67 loc) · 1.98 KB
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
import isBefore from 'date-fns/isBefore';
import Project from '../../models/project';
import { deleteObjectsFromS3, getObjectKey } from '../aws.controller';
import createApplicationErrorClass from '../../utils/createApplicationErrorClass';
const ProjectDeletionError = createApplicationErrorClass(
'ProjectDeletionError'
);
async function deleteFilesFromS3(files) {
const filteredFiles = files
.filter((file) => {
const isValidFile =
file.url &&
(file.url.includes(process.env.S3_BUCKET_URL_BASE) ||
file.url.includes(process.env.S3_BUCKET)) &&
(!process.env.S3_DATE ||
(process.env.S3_DATE &&
isBefore(new Date(process.env.S3_DATE), new Date(file.createdAt))));
return isValidFile;
})
.map((file) => getObjectKey(file.url));
try {
await deleteObjectsFromS3(filteredFiles);
} catch (error) {
console.error('Failed to delete files from S3: ', error);
}
}
export default async function deleteProject(req, res) {
const sendFailure = (error) => {
res.status(error.code).json({ message: error.message });
};
function sendProjectNotFound() {
sendFailure(
new ProjectDeletionError('Project with that id does not exist', {
code: 404
})
);
}
try {
const project = await Project.findById(req.params.project_id);
if (!project) {
sendFailure(
new ProjectDeletionError('Project with that id does not exist', {
code: 404
})
);
return;
}
if (!project.user.equals(req.user._id)) {
sendFailure(
new ProjectDeletionError(
'Authenticated user does not match owner of project',
{ code: 403 }
)
);
return;
}
await deleteFilesFromS3(project.files);
await project.deleteOne();
res.status(200).end();
} catch (error) {
if (error.name === 'CastError' && error.kind === 'ObjectId') {
sendProjectNotFound();
} else {
sendFailure(error);
}
}
}