From cb8f5f59d0c2f97df6384a631ac5185c43a69bda Mon Sep 17 00:00:00 2001 From: Jonathan Cremin Date: Mon, 6 Jun 2016 20:57:34 +0100 Subject: [PATCH] Add retries to upload --- lib/sftp.js | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/lib/sftp.js b/lib/sftp.js index f02bc9d..d61cb8a 100644 --- a/lib/sftp.js +++ b/lib/sftp.js @@ -15,7 +15,7 @@ export function get(remotePath) { .then(() => sftp.get(join('hostr', 'uploads', remotePath), { encoding: null })); } -export function upload(localPath, remotePath) { +function sendFile(localPath, remotePath) { const sftp = new Client(); return sftp.connect({ host: process.env.SFTP_HOST, @@ -24,6 +24,25 @@ export function upload(localPath, remotePath) { password: process.env.SFTP_PASSWORD, }) .then(() => sftp.put(localPath, remotePath, true)) - .catch(() => sftp.mkdir(dirname(remotePath), true) - .then(() => sftp.put(localPath, remotePath, true))); + .catch((err) => { + if (err.message === 'No such file') { + debug('Creating directory'); + return sftp.mkdir(dirname(remotePath), true) + .then(() => sftp.put(localPath, remotePath, true)); + } + throw err; + }); +} + +export function *upload(localPath, remotePath) { + let done = false; + for (let retries = 0; retries < 5; retries++) { + try { + done = yield sendFile(localPath, remotePath); + break; + } catch (err) { + debug('retry'); + } + } + return done; }