Sharkey/src/api/serializers/drive-file.ts

75 lines
1.4 KiB
TypeScript
Raw Normal View History

2016-12-28 22:49:51 +00:00
/**
* Module dependencies
*/
import * as mongo from 'mongodb';
import DriveFile from '../models/drive-file';
2017-02-16 07:55:01 +00:00
import serializeDriveFolder from './drive-folder';
2016-12-28 22:49:51 +00:00
import serializeDriveTag from './drive-tag';
2017-01-02 21:03:19 +00:00
import deepcopy = require('deepcopy');
2017-01-17 00:17:52 +00:00
import config from '../../conf';
2016-12-28 22:49:51 +00:00
/**
* Serialize a drive file
*
2017-03-01 08:37:01 +00:00
* @param {any} file
* @param {any} options?
* @return {Promise<any>}
2016-12-28 22:49:51 +00:00
*/
export default (
file: any,
options?: {
2017-02-16 07:55:01 +00:00
detail: boolean
2016-12-28 22:49:51 +00:00
}
2017-03-01 08:37:01 +00:00
) => new Promise<any>(async (resolve, reject) => {
2017-02-16 07:55:01 +00:00
const opts = Object.assign({
detail: false
}, options);
2016-12-28 22:49:51 +00:00
let _file: any;
// Populate the file if 'file' is ID
if (mongo.ObjectID.prototype.isPrototypeOf(file)) {
_file = await DriveFile.findOne({
_id: file
}, {
2017-03-01 08:37:01 +00:00
fields: {
data: false
}
});
2016-12-28 22:49:51 +00:00
} else if (typeof file === 'string') {
_file = await DriveFile.findOne({
_id: new mongo.ObjectID(file)
}, {
2017-03-01 08:37:01 +00:00
fields: {
data: false
}
});
2016-12-28 22:49:51 +00:00
} 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)}`;
2017-02-16 07:55:01 +00:00
if (opts.detail && _file.folder_id) {
// Populate folder
_file.folder = await serializeDriveFolder(_file.folder_id, {
detail: true
});
}
if (opts.detail && _file.tags) {
2016-12-28 22:49:51 +00:00
// Populate tags
_file.tags = await _file.tags.map(async (tag: any) =>
await serializeDriveTag(tag)
);
}
resolve(_file);
});