summaryrefslogtreecommitdiff
path: root/src/api/serializers/drive-file.ts
blob: 65fe7d6d2609d65af89463c981ee205f00a79a94 (plain)
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
'use strict';

/**
 * Module dependencies
 */
import * as mongo from 'mongodb';
import DriveFile from '../models/drive-file';
import serializeDriveTag from './drive-tag';
import deepcopy = require('deepcopy');
import config from '../../conf';

/**
 * Serialize a drive file
 *
 * @param {Object} file
 * @param {Object} options?
 * @return {Promise<Object>}
 */
export default (
	file: any,
	options?: {
		includeTags: boolean
	}
) => new Promise<Object>(async (resolve, reject) => {
	const opts = options || {
		includeTags: true
	};

	let _file: any;

	// Populate the file if 'file' is ID
	if (mongo.ObjectID.prototype.isPrototypeOf(file)) {
		_file = await DriveFile.findOne({
			_id: file
		}, {
			fields: {
				data: false
			}
		});
	} else if (typeof file === 'string') {
		_file = await DriveFile.findOne({
			_id: new mongo.ObjectID(file)
		}, {
			fields: {
				data: false
			}
		});
	} else {
		_file = deepcopy(file);
	}

	// Rename _id to id
	_file.id = _file._id;
	delete _file._id;

	delete _file.data;

	_file.url = `${config.drive_url}/${_file.id}/${encodeURIComponent(_file.name)}`;

	if (opts.includeTags && _file.tags) {
		// Populate tags
		_file.tags = await _file.tags.map(async (tag: any) =>
			await serializeDriveTag(tag)
		);
	}

	resolve(_file);
});