summaryrefslogtreecommitdiff
path: root/src/api
diff options
context:
space:
mode:
authorotofune <otofune@gmail.com>2017-11-14 05:10:28 +0900
committerotofune <otofune@gmail.com>2017-11-14 05:10:28 +0900
commitd8a3b4ff1d418eb2aab30237d797dc4844858abe (patch)
treeb5ed4632fc793bdb5c31cbe3dc81f93e8ffdfa21 /src/api
parentadd-file-to-drive - 見通しを良くする (diff)
downloadsharkey-d8a3b4ff1d418eb2aab30237d797dc4844858abe.tar.gz
sharkey-d8a3b4ff1d418eb2aab30237d797dc4844858abe.tar.bz2
sharkey-d8a3b4ff1d418eb2aab30237d797dc4844858abe.zip
add-file-to-drive - 責務の分割とテンポラリファイルを削除するように
Diffstat (limited to 'src/api')
-rw-r--r--src/api/common/add-file-to-drive.ts61
1 files changed, 35 insertions, 26 deletions
diff --git a/src/api/common/add-file-to-drive.ts b/src/api/common/add-file-to-drive.ts
index eeb92005ae..6a728d0d1a 100644
--- a/src/api/common/add-file-to-drive.ts
+++ b/src/api/common/add-file-to-drive.ts
@@ -34,7 +34,7 @@ const addToGridFS = (name: string, readable: stream.Readable, type: string, meta
const addFile = async (
user: any,
- file: string | stream.Readable,
+ path: string,
name: string = null,
comment: string = null,
folderId: mongodb.ObjectID = null,
@@ -42,30 +42,6 @@ const addFile = async (
) => {
log(`registering ${name} (user: ${user.username})`);
- // Get file path
- const path = await new Promise((res: (v: string) => void, rej) => {
- if (typeof file === 'string') {
- res(file);
- return;
- }
- if (typeof file === 'object' && typeof file.read === 'function') {
- tmpFile()
- .then(path => {
- const readable: stream.Readable = file;
- const writable = fs.createWriteStream(path);
- readable
- .on('error', rej)
- .on('end', () => {
- res(path);
- })
- .pipe(writable)
- .on('error', rej);
- })
- .catch(rej);
- }
- rej(new Error('un-compatible file.'));
- });
-
// Calculate hash, get content type and get file size
const [hash, [mime, ext], size] = await Promise.all([
// hash
@@ -212,7 +188,40 @@ const addFile = async (
* @return Object that represents added file
*/
export default (user: any, file: string | stream.Readable, ...args) => new Promise<any>((resolve, reject) => {
- addFile(user, file, ...args)
+ // Get file path
+ new Promise((res: (v: [string, boolean]) => void, rej) => {
+ if (typeof file === 'string') {
+ res([file, false]);
+ return;
+ }
+ if (typeof file === 'object' && typeof file.read === 'function') {
+ tmpFile()
+ .then(path => {
+ const readable: stream.Readable = file;
+ const writable = fs.createWriteStream(path);
+ readable
+ .on('error', rej)
+ .on('end', () => {
+ res([path, true]);
+ })
+ .pipe(writable)
+ .on('error', rej);
+ })
+ .catch(rej);
+ }
+ rej(new Error('un-compatible file.'));
+ }).then(([path, remove]): Promise<any> => new Promise((res, rej) => {
+ addFile(user, path, ...args)
+ .then(file => {
+ res(file)
+ if (remove) {
+ fs.unlink(path, (e) => {
+ if (e) log(e.stack)
+ })
+ }
+ })
+ .catch(rej)
+ }))
.then(file => {
log(`drive file has been created ${file._id}`);
resolve(file);