Skip to content

Commit

Permalink
refactor: reuse random filename in filesystem image provider
Browse files Browse the repository at this point in the history
Signed-off-by: Yukai Huang <[email protected]>
  • Loading branch information
Yukaii committed Jun 5, 2024
1 parent d157fde commit c5e2452
Showing 1 changed file with 1 addition and 19 deletions.
20 changes: 1 addition & 19 deletions lib/imageRouter/filesystem.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,24 +16,6 @@ function randomFilename () {
return `upload_${buf.toString('hex')}`
}

/**
* pick a filename not exist in filesystem
* maximum attempt 5 times
*/
function pickFilename (defaultFilename) {
let retryCounter = 5
let filename = defaultFilename
const extname = path.extname(defaultFilename)
while (retryCounter-- > 0) {
if (fs.existsSync(path.join(config.uploadsPath, filename))) {
filename = `${randomFilename()}${extname}`
continue
}
return filename
}
throw new Error('file exists.')
}

exports.uploadImage = function (imagePath, callback) {
if (!imagePath || typeof imagePath !== 'string') {
callback(new Error('Image path is missing or wrong'), null)
Expand All @@ -47,7 +29,7 @@ exports.uploadImage = function (imagePath, callback) {

let filename = path.basename(imagePath)
try {
filename = pickFilename(path.basename(imagePath))
filename = randomFilename()
} catch (e) {
return callback(e, null)
}
Expand Down

0 comments on commit c5e2452

Please sign in to comment.