From d8a3b4ff1d418eb2aab30237d797dc4844858abe Mon Sep 17 00:00:00 2001 From: otofune Date: Tue, 14 Nov 2017 05:10:28 +0900 Subject: [PATCH] =?UTF-8?q?add-file-to-drive=20-=20=E8=B2=AC=E5=8B=99?= =?UTF-8?q?=E3=81=AE=E5=88=86=E5=89=B2=E3=81=A8=E3=83=86=E3=83=B3=E3=83=9D?= =?UTF-8?q?=E3=83=A9=E3=83=AA=E3=83=95=E3=82=A1=E3=82=A4=E3=83=AB=E3=82=92?= =?UTF-8?q?=E5=89=8A=E9=99=A4=E3=81=99=E3=82=8B=E3=82=88=E3=81=86=E3=81=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/api/common/add-file-to-drive.ts | 61 +++++++++++++++++------------ 1 file 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 eeb92005a..6a728d0d1 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((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 => 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);