Skip to content

Commit bda0cd9

Browse files
feat: Retry failed requests
Adds retry logic around uploads to attempt to retry 3 times on failed uploads. Fixes #82
1 parent d72094b commit bda0cd9

File tree

1 file changed

+28
-24
lines changed

1 file changed

+28
-24
lines changed

netlify-plugin-cloudinary/src/lib/cloudinary.ts

Lines changed: 28 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -203,34 +203,38 @@ export async function getCloudinaryUrl(options: CloudinaryOptions) {
203203
}
204204

205205
let results
206+
const maxAttempts = 3;
206207

207-
if (canSignUpload) {
208-
// We need an API Key and Secret to use signed uploading
209-
210-
try {
211-
results = await cloudinary.uploader.upload(fullPath, {
212-
...uploadOptions,
213-
})
214-
} catch (error) {
215-
console.error(`[Cloudinary] ${ERROR_ASSET_UPLOAD}`)
216-
console.error(`[Cloudinary] \tpath: ${fullPath}`)
217-
throw Error(ERROR_ASSET_UPLOAD)
218-
}
219-
} else {
220-
// If we want to avoid signing our uploads, we don't need our API Key and Secret,
221-
// however, we need to provide an uploadPreset
208+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
222209
try {
223-
results = await cloudinary.uploader.unsigned_upload(
224-
fullPath,
225-
uploadPreset,
226-
{
210+
if (canSignUpload) {
211+
// We need an API Key and Secret to use signed uploading
212+
results = await cloudinary.uploader.upload(fullPath, {
227213
...uploadOptions,
228-
},
229-
)
214+
})
215+
break;
216+
}
217+
else {
218+
// If we want to avoid signing our uploads, we don't need our API Key and Secret,
219+
// however, we need to provide an uploadPreset
220+
results = await cloudinary.uploader.unsigned_upload(
221+
fullPath,
222+
uploadPreset,
223+
{
224+
...uploadOptions,
225+
},
226+
)
227+
break;
228+
}
230229
} catch (error) {
231-
console.error(`[Cloudinary] ${ERROR_ASSET_UPLOAD}`)
232-
console.error(`[Cloudinary] path: ${fullPath}`)
233-
throw Error(ERROR_ASSET_UPLOAD)
230+
console.error(`[Cloudinary] Attempt ${attempt + 1} - ${ERROR_ASSET_UPLOAD}`);
231+
console.error(`[Cloudinary] Attempt ${attempt + 1} - \tpath: ${fullPath}`)
232+
if (attempt === maxAttempts - 1) {
233+
// If it's the last attempt, rethrow the error or handle it accordingly
234+
throw Error(ERROR_ASSET_UPLOAD);
235+
} else {
236+
await new Promise(resolve => setTimeout(resolve, 500));
237+
}
234238
}
235239
}
236240

0 commit comments

Comments
 (0)