From ad18136b0482fe0db00194f6485ea12261482bf8 Mon Sep 17 00:00:00 2001 From: syuilo Date: Tue, 10 Apr 2018 04:02:25 +0900 Subject: [PATCH] Refactor --- src/services/drive/add-file.ts | 22 +++++++++------------- src/services/drive/upload-from-url.ts | 10 ++++------ 2 files changed, 13 insertions(+), 19 deletions(-) diff --git a/src/services/drive/add-file.ts b/src/services/drive/add-file.ts index 4889b357a4..30aae24ba6 100644 --- a/src/services/drive/add-file.ts +++ b/src/services/drive/add-file.ts @@ -23,10 +23,10 @@ const gm = _gm.subClass({ const log = debug('misskey:drive:add-file'); -const tmpFile = (): Promise => new Promise((resolve, reject) => { - tmp.file((e, path) => { +const tmpFile = (): Promise<[string, any]> => new Promise((resolve, reject) => { + tmp.file((e, path, fd, cleanup) => { if (e) return reject(e); - resolve(path); + resolve([path, cleanup]); }); }); @@ -254,18 +254,18 @@ export default (user: any, file: string | stream.Readable, ...args) => new Promi const isStream = typeof file === 'object' && typeof file.read === 'function'; // Get file path - new Promise((res, rej) => { + new Promise<[string, any]>((res, rej) => { if (typeof file === 'string') { - res(file); + res([file, null]); } else if (isStream) { tmpFile() - .then(path => { + .then(([path, cleanup]) => { const readable: stream.Readable = file; const writable = fs.createWriteStream(path); readable .on('error', rej) .on('end', () => { - res(path); + res([path, cleanup]); }) .pipe(writable) .on('error', rej); @@ -275,15 +275,11 @@ export default (user: any, file: string | stream.Readable, ...args) => new Promi rej(new Error('un-compatible file.')); } }) - .then(path => new Promise((res, rej) => { + .then(([path, cleanup]) => new Promise((res, rej) => { addFile(user, path, ...args) .then(file => { res(file); - if (isStream) { - fs.unlink(path, e => { - if (e) console.error(e.stack); - }); - } + if (cleanup) cleanup(); }) .catch(rej); })) diff --git a/src/services/drive/upload-from-url.ts b/src/services/drive/upload-from-url.ts index b3bb47033f..fc8805260c 100644 --- a/src/services/drive/upload-from-url.ts +++ b/src/services/drive/upload-from-url.ts @@ -19,10 +19,10 @@ export default async (url, user, folderId = null, uri = null): Promise((res, rej) => { - tmp.file((e, path) => { + const [path, cleanup] = await new Promise<[string, any]>((res, rej) => { + tmp.file((e, path, fd, cleanup) => { if (e) return rej(e); - res(path); + res([path, cleanup]); }); }); @@ -44,9 +44,7 @@ export default async (url, user, folderId = null, uri = null): Promise { - if (e) console.error(e); - }); + cleanup(); return driveFile; };