aboutsummaryrefslogtreecommitdiff
path: root/src/api/routes/files/tagAddBatchPOST.js
blob: de41d8f0bf8c1ff1ae46f676fe8ba1d2c7abcda3 (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
40
const Route = require('../../structures/Route');

class tagAddBatchPOST extends Route {
	constructor() {
		super('/file/tag/addBatch', 'post');
	}

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

		// Make sure the file belongs to the user
		const file = await db.table('files').where({ id: fileId, userId: user.id }).first();
		if (!file) return res.status(400).json({ message: 'File doesn\'t exist.' });

		const errors = {};
		const addedTags = [];
		for await (const tagName of tagNames) {
			try {
				const tag = await db.table('tags').where({ name: tagName, userId: user.id }).first();
				if (!tag) throw new Error('Tag doesn\'t exist in the database');
				await db.table('fileTags').insert({ fileId, tagId: tag.id }).wasMutated();

				addedTags.push(tag);
			} catch (e) {
				errors[tagName] = e.message;
			}
		}

		return res.json({
			message: 'Successfully added tags to file',
			data: { fileId, tags: addedTags },
			errors
		});
		// eslint-disable-next-line consistent-return
	}
}

module.exports = tagAddBatchPOST;