2016-12-28 22:49:51 +00:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Module dependencies
|
|
|
|
*/
|
|
|
|
import * as fs from 'fs';
|
|
|
|
import * as mongo from 'mongodb';
|
|
|
|
import File from '../../../models/drive-file';
|
|
|
|
import { validateFileName } from '../../../models/drive-file';
|
|
|
|
import User from '../../../models/user';
|
|
|
|
import serialize from '../../../serializers/drive-file';
|
|
|
|
import create from '../../../common/add-file-to-drive';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create a file
|
|
|
|
*
|
2017-03-01 08:37:01 +00:00
|
|
|
* @param {any} file
|
|
|
|
* @param {any} params
|
|
|
|
* @param {any} user
|
|
|
|
* @return {Promise<any>}
|
2016-12-28 22:49:51 +00:00
|
|
|
*/
|
|
|
|
module.exports = (file, params, user) =>
|
|
|
|
new Promise(async (res, rej) =>
|
|
|
|
{
|
2017-02-11 16:39:27 +00:00
|
|
|
if (file == null) {
|
|
|
|
return rej('file is required');
|
|
|
|
}
|
|
|
|
|
2016-12-28 22:49:51 +00:00
|
|
|
const buffer = fs.readFileSync(file.path);
|
2017-01-24 12:50:59 +00:00
|
|
|
fs.unlink(file.path, (err) => { if (err) console.log(err) });
|
2016-12-28 22:49:51 +00:00
|
|
|
|
|
|
|
// Get 'name' parameter
|
|
|
|
let name = file.originalname;
|
|
|
|
if (name !== undefined && name !== null) {
|
|
|
|
name = name.trim();
|
|
|
|
if (name.length === 0) {
|
|
|
|
name = null;
|
|
|
|
} else if (name === 'blob') {
|
|
|
|
name = null;
|
|
|
|
} else if (!validateFileName(name)) {
|
|
|
|
return rej('invalid name');
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
name = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get 'folder_id' parameter
|
|
|
|
let folder = params.folder_id;
|
2017-02-12 16:49:17 +00:00
|
|
|
if (folder === undefined || folder === null) {
|
2016-12-28 22:49:51 +00:00
|
|
|
folder = null;
|
|
|
|
} else {
|
|
|
|
folder = new mongo.ObjectID(folder);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create file
|
|
|
|
const driveFile = await create(user, buffer, name, null, folder);
|
|
|
|
|
|
|
|
// Serialize
|
|
|
|
const fileObj = await serialize(driveFile);
|
|
|
|
|
|
|
|
// Response
|
|
|
|
res(fileObj);
|
|
|
|
});
|