perf: no try-catch block on cloudflare cache purge

This commit is contained in:
Bobby Wibowo 2022-07-14 14:41:55 +07:00
parent edbb6ef9f0
commit ac63f8b76d
No known key found for this signature in database
GPG Key ID: 51C3A1E1E22D26CF

View File

@ -225,38 +225,42 @@ const cloudflarePurgeCacheQueue = cloudflareAuth && fastq.promise(async chunk =>
logger.log(`${prefix}: ${message}`) logger.log(`${prefix}: ${message}`)
} }
try { const response = await fetch(url, {
const purge = await fetch(url, { method: 'POST',
method: 'POST', body: JSON.stringify({ files: chunk }),
body: JSON.stringify({ files: chunk }), headers
headers })
}) .then(res => res.json())
const response = await purge.json() .catch(error => error)
const hasErrorsArray = Array.isArray(response.errors) && response.errors.length // If fetch errors out, instead of API responding with API errors
if (hasErrorsArray) { if (response instanceof Error) {
const rateLimit = response.errors.find(error => /rate limit/i.test(error.message)) const errorString = response.toString()
if (rateLimit && i < MAX_TRIES - 1) {
_log(`${rateLimit.code}: ${rateLimit.message}. Retrying in a minute\u2026`)
await new Promise(resolve => setTimeout(resolve, 60000))
continue
}
}
result.success = response.success
result.errors = hasErrorsArray
? response.errors.map(error => `${error.code}: ${error.message}`)
: []
} catch (error) {
const errorString = error.toString()
if (i < MAX_TRIES - 1) { if (i < MAX_TRIES - 1) {
_log(`${errorString}. Retrying in 5 seconds\u2026`) _log(`${errorString}. Retrying in 5 seconds\u2026`)
await new Promise(resolve => setTimeout(resolve, 5000)) await new Promise(resolve => setTimeout(resolve, 5000))
continue continue
} }
result.errors = [errorString] result.errors = [errorString]
break
} }
// If API reponds with API errors
const hasErrorsArray = Array.isArray(response.errors) && response.errors.length
if (hasErrorsArray) {
const rateLimit = response.errors.find(error => /rate limit/i.test(error.message))
if (rateLimit && i < MAX_TRIES - 1) {
_log(`${rateLimit.code}: ${rateLimit.message}. Retrying in a minute\u2026`)
await new Promise(resolve => setTimeout(resolve, 60000))
continue
}
}
// If succeeds or out of retries
result.success = response.success
result.errors = hasErrorsArray
? response.errors.map(error => `${error.code}: ${error.message}`)
: []
break break
} }
@ -742,9 +746,10 @@ self.purgeCloudflareCache = async (names, uploads, thumbs) => {
} }
const results = [] const results = []
await Promise.all(chunks.map(async chunk => for (const chunk of chunks) {
results.push(await cloudflarePurgeCacheQueue.push(chunk)) const result = await cloudflarePurgeCacheQueue.push(chunk)
)) results.push(result)
}
return results return results
} }