2022-03-22 18:19:46 +01:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
const uuid = require('uuid/v4');
|
|
|
|
const { trimChars, trimCharsEnd, trimCharsStart } = require('lodash/fp');
|
|
|
|
|
|
|
|
// TODO: to use once https://github.com/strapi/strapi/pull/12534 is merged
|
|
|
|
// const { joinBy } = require('@strapi/utils');
|
|
|
|
|
|
|
|
const folderModel = 'plugin::upload.folder';
|
|
|
|
|
|
|
|
const joinBy = (joint, ...args) => {
|
|
|
|
const trim = trimChars(joint);
|
|
|
|
const trimEnd = trimCharsEnd(joint);
|
|
|
|
const trimStart = trimCharsStart(joint);
|
|
|
|
|
|
|
|
return args.reduce((url, path, index) => {
|
|
|
|
if (args.length === 1) return path;
|
|
|
|
if (index === 0) return trimEnd(path);
|
|
|
|
if (index === args.length - 1) return url + joint + trimStart(path);
|
|
|
|
return url + joint + trim(path);
|
|
|
|
}, '');
|
|
|
|
};
|
|
|
|
|
|
|
|
const generateUID = () => uuid();
|
|
|
|
|
2022-04-06 11:36:13 +02:00
|
|
|
const setLocationAndUID = async folder => {
|
2022-04-05 17:36:09 +02:00
|
|
|
const uid = generateUID();
|
2022-04-06 11:36:13 +02:00
|
|
|
let parentLocation = '/';
|
2022-03-22 18:19:46 +01:00
|
|
|
if (folder.parent) {
|
|
|
|
const parentFolder = await strapi.entityService.findOne(folderModel, folder.parent);
|
2022-04-06 11:36:13 +02:00
|
|
|
parentLocation = parentFolder.location;
|
2022-03-22 18:19:46 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return Object.assign(folder, {
|
2022-04-05 17:36:09 +02:00
|
|
|
uid,
|
2022-04-06 11:36:13 +02:00
|
|
|
location: joinBy('/', parentLocation, uid),
|
2022-03-22 18:19:46 +01:00
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2022-04-04 14:32:08 +02:00
|
|
|
const deleteByIds = async ids => {
|
|
|
|
const deletedFolders = [];
|
|
|
|
for (const id of ids) {
|
|
|
|
const deletedFolder = await strapi.entityService.delete(folderModel, id);
|
|
|
|
|
|
|
|
deletedFolders.push(deletedFolder);
|
|
|
|
}
|
|
|
|
|
|
|
|
return deletedFolders;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Check if a folder exists in database
|
|
|
|
* @param params query params to find the folder
|
|
|
|
* @returns {Promise<boolean>}
|
|
|
|
*/
|
|
|
|
const exists = async (params = {}) => {
|
|
|
|
const count = await strapi.query(folderModel).count({ where: params });
|
|
|
|
return count > 0;
|
|
|
|
};
|
|
|
|
|
2022-03-22 18:19:46 +01:00
|
|
|
module.exports = {
|
2022-04-04 14:32:08 +02:00
|
|
|
exists,
|
|
|
|
deleteByIds,
|
2022-04-06 11:36:13 +02:00
|
|
|
setLocationAndUID,
|
2022-03-22 18:19:46 +01:00
|
|
|
};
|