-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathlistCollections.js
49 lines (41 loc) · 1.17 KB
/
listCollections.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
import Collection from '../../models/collection';
import User from '../../models/user';
async function getOwnerUserId(req) {
if (req.params.username) {
const user = await User.findByUsername(req.params.username);
if (user && user._id) {
return user._id;
}
} else if (req.user._id) {
return req.user._id;
}
return null;
}
export default async function listCollections(req, res) {
const sendFailure = ({ code = 500, message = 'Something went wrong' }) => {
res.status(code).json({ success: false, message });
};
const sendSuccess = (collections) => {
res.status(200).json(collections);
};
try {
const owner = await getOwnerUserId(req);
if (!owner) {
sendFailure('404', 'User not found');
}
const collections = await Collection.find({ owner }).populate([
{ path: 'owner', select: ['id', 'username'] },
{
path: 'items.project',
select: ['id', 'name', 'slug'],
populate: {
path: 'user',
select: ['username']
}
}
]);
sendSuccess(collections);
} catch (error) {
sendFailure(error.code || 500, error.message || 'Something went wrong');
}
}