aboutsummaryrefslogtreecommitdiff
path: root/src/api/routes/albums/albumPOST.js
blob: 52352a1202a19db2c187eba65c38c8295b6fdbc1 (plain) (blame)
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
const moment = require('moment');
const Route = require('../../structures/Route');

class albumPOST extends Route {
	constructor() {
		super('/album/new', 'post');
	}

	async run(req, res, db, user) {
		if (!req.body) return res.status(400).json({ message: 'No body provided' });
		const { name } = req.body;
		if (!name) return res.status(400).json({ message: 'No name provided' });

		/*
			Check that an album with that name doesn't exist yet
		*/
		const album = await db
			.table('albums')
			.where({ name, userId: user.id })
			.first();
		if (album) return res.status(401).json({ message: "There's already an album with that name" });

		const now = moment.utc().toDate();
		const insertObj = {
			name,
			userId: user.id,
			createdAt: now,
			editedAt: now
		};

		const dbRes = await db.table('albums').insert(insertObj);

		insertObj.id = dbRes.pop();

		return res.json({ message: 'The album was created successfully', data: insertObj });
	}
}

module.exports = albumPOST;