Merge pull request #77 from tycrek/check-existing-ids

pull/78/head
Josh Moore 3 years ago committed by GitHub
commit 69d5b5390d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -64,10 +64,37 @@ router.post('/', (req, res, next) => {
// Fix spaces in originalname
req.file.originalname = req.file.originalname.replace(/\s/g, spaceReplace === '!' ? '' : spaceReplace);
// Save the file information
const resourceId = generateId(generator, resourceIdSize, req.headers['x-ass-gfycat'] || gfyIdSize, req.file.originalname);
// Generate a unique resource ID
let resourceId = '';
// Function to call to generate a fresh ID. Used for multiple attempts in case an ID is already taken
const gen = () => generateId(generator, resourceIdSize, req.headers['x-ass-gfycat'] || gfyIdSize, req.file.originalname);
// Keeps track of the number of attempts in case all ID's are taken
const attempts = {
count: 0,
max: 50
};
// Called by a promise, this will recursively resolve itself until a unique ID is found
function genCheckId(resolve, reject) {
const uniqueId = gen();
attempts.count++;
data.has(uniqueId)
.then((exists) => {
log.debug('ID check', exists ? 'Taken' : 'Available');
return attempts.count - 1 >= attempts.max ? reject(new Error('No ID\'s remaining')) : exists ? genCheckId(resolve, reject) : resolve(uniqueId);
})
.catch(reject);
}
new Promise((resolve, reject) => genCheckId(resolve, reject))
.then((uniqueId) => {
resourceId = uniqueId;
log.debug('Saving data', data.name);
data.put(resourceId.split('.')[0], req.file).then(() => {
})
.then(() => data.put(resourceId.split('.')[0], req.file))
.then(() => {
// Log the upload
const logInfo = `${req.file.originalname} (${req.file.mimetype}, ${formatBytes(req.file.size)})`;
log.success('File uploaded', logInfo, `uploaded by ${users[req.token] ? users[req.token].username : '<token-only>'}`);

Loading…
Cancel
Save