jormungandr-bite/src/server/api/models/drive-folder.ts

78 lines
1.6 KiB
TypeScript
Raw Normal View History

2018-02-01 16:06:01 -07:00
import * as mongo from 'mongodb';
import deepcopy = require('deepcopy');
2018-03-28 10:20:40 -06:00
import db from '../../../db/mongodb';
2018-02-01 16:06:01 -07:00
import DriveFile from './drive-file';
2017-01-16 17:12:33 -07:00
2018-02-01 16:06:01 -07:00
const DriveFolder = db.get<IDriveFolder>('drive_folders');
export default DriveFolder;
export type IDriveFolder = {
_id: mongo.ObjectID;
2018-03-28 23:48:47 -06:00
createdAt: Date;
2018-02-01 16:21:30 -07:00
name: string;
2018-03-28 23:48:47 -06:00
userId: mongo.ObjectID;
parentId: mongo.ObjectID;
2018-02-01 16:06:01 -07:00
};
2016-12-28 15:49:51 -07:00
export function isValidFolderName(name: string): boolean {
return (
(name.trim().length > 0) &&
(name.length <= 200)
);
}
2018-02-01 16:06:01 -07:00
/**
* Pack a drive folder for API response
*
* @param {any} folder
* @param {any} options?
* @return {Promise<any>}
*/
export const pack = (
folder: any,
options?: {
detail: boolean
}
) => new Promise<any>(async (resolve, reject) => {
const opts = Object.assign({
detail: false
}, options);
let _folder: any;
// Populate the folder if 'folder' is ID
if (mongo.ObjectID.prototype.isPrototypeOf(folder)) {
_folder = await DriveFolder.findOne({ _id: folder });
} else if (typeof folder === 'string') {
_folder = await DriveFolder.findOne({ _id: new mongo.ObjectID(folder) });
} else {
_folder = deepcopy(folder);
}
// Rename _id to id
_folder.id = _folder._id;
delete _folder._id;
if (opts.detail) {
const childFoldersCount = await DriveFolder.count({
2018-03-28 23:48:47 -06:00
parentId: _folder.id
2018-02-01 16:06:01 -07:00
});
const childFilesCount = await DriveFile.count({
2018-03-28 23:48:47 -06:00
'metadata.folderId': _folder.id
2018-02-01 16:06:01 -07:00
});
2018-03-28 23:48:47 -06:00
_folder.foldersCount = childFoldersCount;
_folder.filesCount = childFilesCount;
2018-02-01 16:06:01 -07:00
}
2018-03-28 23:48:47 -06:00
if (opts.detail && _folder.parentId) {
2018-02-01 16:06:01 -07:00
// Populate parent folder
2018-03-28 23:48:47 -06:00
_folder.parent = await pack(_folder.parentId, {
2018-02-01 16:06:01 -07:00
detail: true
});
}
resolve(_folder);
});