1
0
Fork 0
mirror of https://github.com/plankanban/planka.git synced 2025-07-19 21:29:43 +02:00
planka/server/api/controllers/projects/update-background-image.js

105 lines
2.2 KiB
JavaScript
Raw Normal View History

const util = require('util');
const rimraf = require('rimraf');
const { v4: uuid } = require('uuid');
2020-05-26 00:46:04 +05:00
const Errors = {
PROJECT_NOT_FOUND: {
projectNotFound: 'Project not found',
},
NO_FILE_WAS_UPLOADED: {
noFileWasUploaded: 'No file was uploaded',
},
FILE_IS_NOT_IMAGE: {
fileIsNotImage: 'File is not image',
},
2020-05-26 00:46:04 +05:00
};
module.exports = {
inputs: {
id: {
type: 'string',
regex: /^[0-9]+$/,
required: true,
},
},
exits: {
projectNotFound: {
responseType: 'notFound',
},
noFileWasUploaded: {
responseType: 'unprocessableEntity',
},
fileIsNotImage: {
responseType: 'unprocessableEntity',
},
2020-05-26 00:46:04 +05:00
uploadError: {
responseType: 'unprocessableEntity',
},
},
async fn(inputs, exits) {
const { currentUser } = this.req;
2020-05-26 00:46:04 +05:00
let project = await Project.findOne(inputs.id);
if (!project) {
throw Errors.PROJECT_NOT_FOUND;
}
const isProjectManager = await sails.helpers.users.isProjectManager(currentUser.id, project.id);
if (!isProjectManager) {
throw Errors.PROJECT_NOT_FOUND; // Forbidden
}
const upload = util.promisify((options, callback) =>
this.req.file('file').upload(options, (error, files) => callback(error, files)),
);
2020-05-26 00:46:04 +05:00
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;
}
2020-05-26 00:46:04 +05:00
const file = _.last(files);
2020-05-26 00:46:04 +05:00
const fileData = await sails.helpers.projects
.processUploadedBackgroundImageFile(file)
.intercept('fileIsNotImage', () => {
try {
rimraf.sync(file.fd);
} catch (error) {
console.warn(error.stack); // eslint-disable-line no-console
2020-05-26 00:46:04 +05:00
}
return Errors.FILE_IS_NOT_IMAGE;
2020-05-26 00:46:04 +05:00
});
2022-12-26 21:10:50 +01:00
project = await sails.helpers.projects.updateOne.with({
record: project,
values: {
backgroundImage: fileData,
},
2022-12-26 21:10:50 +01:00
request: this.req,
});
if (!project) {
throw Errors.PROJECT_NOT_FOUND;
}
return exits.success({
item: project,
});
2020-05-26 00:46:04 +05:00
},
};