-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathaddProjectToCollection.js
77 lines (64 loc) · 1.85 KB
/
addProjectToCollection.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
import Collection from '../../models/collection';
import Project from '../../models/project';
export default function addProjectToCollection(req, res) {
const owner = req.user._id;
const { id: collectionId, projectId } = req.params;
const collectionPromise = Collection.findById(collectionId).populate(
'items.project',
'_id'
);
const projectPromise = Project.findById(projectId);
function sendFailure(code, message) {
res.status(code).json({ success: false, message });
}
function sendSuccess(collection) {
res.status(200).json(collection);
}
function updateCollection([collection, project]) {
if (collection == null) {
sendFailure(404, 'Collection not found');
return null;
}
if (project == null) {
sendFailure(404, 'Project not found');
return null;
}
if (!collection.owner.equals(owner)) {
sendFailure(403, 'User does not own this collection');
return null;
}
const projectInCollection = collection.items.find(
(p) => p.projectId === project._id
);
if (projectInCollection) {
sendFailure(404, 'Project already in collection');
return null;
}
try {
collection.items.push({ project });
return collection.save();
} catch (error) {
console.error(error);
sendFailure(500, error.message);
return null;
}
}
function populateReferences(collection) {
return Collection.populate(collection, [
{ path: 'owner', select: ['id', 'username'] },
{
path: 'items.project',
select: ['id', 'name', 'slug', 'visibility'],
populate: {
path: 'user',
select: ['username']
}
}
]);
}
return Promise.all([collectionPromise, projectPromise])
.then(updateCollection)
.then(populateReferences)
.then(sendSuccess)
.catch(sendFailure);
}