jormungandr-bite/src/server/api/endpoints/drive/files/update.ts

76 lines
1.7 KiB
TypeScript
Raw Normal View History

2016-12-28 15:49:51 -07:00
/**
* Module dependencies
*/
2017-03-08 11:50:09 -07:00
import $ from 'cafy';
2016-12-28 15:49:51 -07:00
import DriveFolder from '../../../models/drive-folder';
2018-02-03 22:52:33 -07:00
import DriveFile, { validateFileName, pack } from '../../../models/drive-file';
2017-11-16 07:46:36 -07:00
import { publishDriveStream } from '../../../event';
2016-12-28 15:49:51 -07:00
/**
* Update a file
*
2017-03-01 01:37:01 -07:00
* @param {any} params
* @param {any} user
* @return {Promise<any>}
2016-12-28 15:49:51 -07:00
*/
2017-03-03 12:28:38 -07:00
module.exports = (params, user) => new Promise(async (res, rej) => {
2018-03-28 23:48:47 -06:00
// Get 'fileId' parameter
const [fileId, fileIdErr] = $(params.fileId).id().$;
if (fileIdErr) return rej('invalid fileId param');
2017-02-11 14:01:31 -07:00
2017-03-03 03:33:14 -07:00
// Fetch file
2016-12-28 15:49:51 -07:00
const file = await DriveFile
.findOne({
2017-03-03 03:33:14 -07:00
_id: fileId,
2018-03-28 23:48:47 -06:00
'metadata.userId': user._id
2016-12-28 15:49:51 -07:00
});
if (file === null) {
return rej('file-not-found');
}
// Get 'name' parameter
2017-03-08 11:50:09 -07:00
const [name, nameErr] = $(params.name).optional.string().pipe(validateFileName).$;
2017-03-03 03:33:14 -07:00
if (nameErr) return rej('invalid name param');
if (name) file.filename = name;
2016-12-28 15:49:51 -07:00
2018-03-28 23:48:47 -06:00
// Get 'folderId' parameter
const [folderId, folderIdErr] = $(params.folderId).optional.nullable.id().$;
if (folderIdErr) return rej('invalid folderId param');
2017-03-03 03:33:14 -07:00
2017-02-12 09:49:17 -07:00
if (folderId !== undefined) {
if (folderId === null) {
2018-03-28 23:48:47 -06:00
file.metadata.folderId = null;
2016-12-28 15:49:51 -07:00
} else {
2017-03-03 03:33:14 -07:00
// Fetch folder
2017-02-12 09:49:17 -07:00
const folder = await DriveFolder
2016-12-28 15:49:51 -07:00
.findOne({
_id: folderId,
2018-03-28 23:48:47 -06:00
userId: user._id
2016-12-28 15:49:51 -07:00
});
if (folder === null) {
2017-02-12 09:17:44 -07:00
return rej('folder-not-found');
2016-12-28 15:49:51 -07:00
}
2018-03-28 23:48:47 -06:00
file.metadata.folderId = folder._id;
2016-12-28 15:49:51 -07:00
}
}
await DriveFile.update(file._id, {
$set: {
filename: file.filename,
2018-03-28 23:48:47 -06:00
'metadata.folderId': file.metadata.folderId
}
2017-02-08 09:37:50 -07:00
});
2016-12-28 15:49:51 -07:00
// Serialize
2018-02-01 16:21:30 -07:00
const fileObj = await pack(file);
2017-11-05 23:18:45 -07:00
2016-12-28 15:49:51 -07:00
// Response
res(fileObj);
2017-11-16 07:46:36 -07:00
// Publish file_updated event
publishDriveStream(user._id, 'file_updated', fileObj);
2016-12-28 15:49:51 -07:00
});