Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Media library folders and files can get unintentionally deleted #16759

Merged
merged 8 commits into from May 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 28 additions & 0 deletions api-tests/core/upload/admin/folder-file.test.api.js
Expand Up @@ -220,6 +220,34 @@ describe('Bulk actions for folders & files', () => {
const existingfoldersIds = resFolder.body.data.map((f) => f.id);
expect(existingfoldersIds).toEqual(expect.not.arrayContaining([folder.id]));
});

test('Can delete folders without deleting others with similar path', async () => {
// Ensure the folder algo does not only delete by folders that start with the same path (startswith /1 matches /10 too)

// Delete all previous folders, so first file path is /1
await rq
.get('/upload/folders')
.then((res) => res.body.data.map((f) => f.id))
.then((folderIds) => rq.post('/upload/actions/bulk-delete', { body: { folderIds } }));

// Create folders
const folder1 = await createFolder('folderToDelete', null);
for (let i = 0; i < 20; i++) {
await createFolder(`folderToKeep-${i}`, null);
}
// Delete folder1
await rq.post('/upload/actions/bulk-delete', {
body: { folderIds: [folder1.id] },
});

const folderIds = await rq
.get('/upload/folders')
.then((res) => res.body.data.map((f) => f.id));

// Should include all folders except the one we deleted
expect(folderIds.length).toBe(20);
expect(folderIds).toEqual(expect.not.arrayContaining([folder1.id]));
});
});

describe('move', () => {
Expand Down
12 changes: 9 additions & 3 deletions packages/core/upload/server/services/folder.js
Expand Up @@ -56,16 +56,22 @@ const deleteByIds = async (ids = []) => {
// delete files
const filesToDelete = await strapi.db.query(FILE_MODEL_UID).findMany({
where: {
$or: pathsToDelete.map((path) => ({ folderPath: { $startsWith: path } })),
$or: pathsToDelete.flatMap((path) => [
{ folderPath: { $eq: path } },
{ folderPath: { $startsWith: `${path}/` } },
]),
},
});

await Promise.all(filesToDelete.map((file) => getService('upload').remove(file)));

// delete folders
// delete folders and subfolders
const { count: totalFolderNumber } = await strapi.db.query(FOLDER_MODEL_UID).deleteMany({
where: {
$or: pathsToDelete.map((path) => ({ path: { $startsWith: path } })),
$or: pathsToDelete.flatMap((path) => [
{ path: { $eq: path } },
{ path: { $startsWith: `${path}/` } },
]),
},
});

Expand Down