1
0
Fork 0
mirror of https://github.com/plankanban/planka.git synced 2025-07-19 05:09:43 +02:00

fix: Change mechanics of file uploading

This commit is contained in:
Maksim Eltyshev 2022-08-26 02:45:27 +02:00
parent af71a96624
commit 542c4a845c
10 changed files with 375 additions and 317 deletions

View file

@ -1,7 +1,17 @@
const util = require('util');
const rimraf = require('rimraf');
const { v4: uuid } = require('uuid');
const Errors = {
USER_NOT_FOUND: {
userNotFound: 'User not found',
},
NO_FILE_WAS_UPLOADED: {
noFileWasUploaded: 'No file was uploaded',
},
FILE_IS_NOT_IMAGE: {
fileIsNotImage: 'File is not image',
},
};
module.exports = {
@ -17,6 +27,12 @@ module.exports = {
userNotFound: {
responseType: 'notFound',
},
noFileWasUploaded: {
responseType: 'unprocessableEntity',
},
fileIsNotImage: {
responseType: 'unprocessableEntity',
},
uploadError: {
responseType: 'unprocessableEntity',
},
@ -38,33 +54,53 @@ module.exports = {
user = currentUser;
}
this.req
.file('file')
.upload(sails.helpers.utils.createUserAvatarReceiver(), async (error, files) => {
if (error) {
return exits.uploadError(error.message);
}
const upload = util.promisify((options, callback) =>
this.req.file('file').upload(options, (error, files) => callback(error, files)),
);
if (files.length === 0) {
return exits.uploadError('No file was uploaded');
}
user = await sails.helpers.users.updateOne(
user,
{
avatarDirname: files[0].extra.dirname,
},
currentUser,
this.req,
);
if (!user) {
throw Errors.USER_NOT_FOUND;
}
return exits.success({
item: user.toJSON(),
});
let files;
try {
files = await upload({
saveAs: uuid(),
maxBytes: null,
});
} catch (error) {
return exits.uploadError(error.message); // TODO: add error
}
if (files.length === 0) {
throw Errors.NO_FILE_WAS_UPLOADED;
}
const file = _.last(files);
const fileData = await sails.helpers.users
.processUploadedAvatarFile(file)
.intercept('fileIsNotImage', () => {
try {
rimraf.sync(file.fd);
} catch (error) {
console.warn(error.stack); // eslint-disable-line no-console
}
return Errors.FILE_IS_NOT_IMAGE;
});
user = await sails.helpers.users.updateOne(
user,
{
avatarDirname: fileData.dirname,
},
currentUser,
this.req,
);
if (!user) {
throw Errors.USER_NOT_FOUND;
}
return exits.success({
item: user,
});
},
};