2016-12-28 15:49:51 -07:00
|
|
|
/**
|
|
|
|
* Module dependencies
|
|
|
|
*/
|
|
|
|
import * as fs from 'fs';
|
2017-03-08 11:50:09 -07:00
|
|
|
import $ from 'cafy';
|
2016-12-28 15:49:51 -07:00
|
|
|
import { validateFileName } from '../../../models/drive-file';
|
|
|
|
import serialize from '../../../serializers/drive-file';
|
|
|
|
import create from '../../../common/add-file-to-drive';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create a file
|
|
|
|
*
|
2017-03-01 01:37:01 -07:00
|
|
|
* @param {any} file
|
|
|
|
* @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 = (file, params, user) => new Promise(async (res, rej) => {
|
2017-02-11 09:39:27 -07:00
|
|
|
if (file == null) {
|
|
|
|
return rej('file is required');
|
|
|
|
}
|
|
|
|
|
2017-11-07 22:58:48 -07:00
|
|
|
// TODO: 非同期にしたい。Promise対応してないんだろうか...
|
2016-12-28 15:49:51 -07:00
|
|
|
const buffer = fs.readFileSync(file.path);
|
2017-03-03 12:28:38 -07:00
|
|
|
fs.unlink(file.path, (err) => { if (err) console.log(err); });
|
2016-12-28 15:49:51 -07: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
|
2017-03-08 11:50:09 -07:00
|
|
|
const [folderId = null, folderIdErr] = $(params.folder_id).optional.nullable.id().$;
|
2017-03-03 03:33:14 -07:00
|
|
|
if (folderIdErr) return rej('invalid folder_id param');
|
2016-12-28 15:49:51 -07:00
|
|
|
|
|
|
|
// Create file
|
2017-03-03 03:33:14 -07:00
|
|
|
const driveFile = await create(user, buffer, name, null, folderId);
|
2016-12-28 15:49:51 -07:00
|
|
|
|
|
|
|
// Serialize
|
|
|
|
const fileObj = await serialize(driveFile);
|
|
|
|
|
|
|
|
// Response
|
|
|
|
res(fileObj);
|
|
|
|
});
|