fix collectionOrder updating + remove index

This commit is contained in:
daniel31x13
2024-02-26 23:59:10 -05:00
parent 4ff7298a3b
commit 4442ce8705
3 changed files with 59 additions and 3 deletions
+19 -3
View File
@@ -19,9 +19,9 @@ const CollectionSelection = ({ links }: Props) => {
const { collections } = useCollectionStore();
const { account, updateAccount } = useAccountStore();
// Use local state to store the collection order so we don't have to wait for a response from the API to update the UI
const [localCollectionOrder, setLocalCollectionOrder] = useState<
number[] | []
>([]);
const [localCollectionOrder, setLocalCollectionOrder] = useState<number[]>(
[]
);
const [active, setActive] = useState("");
const router = useRouter();
@@ -37,6 +37,22 @@ const CollectionSelection = ({ links }: Props) => {
.map((e) => e.id as number), // Use "as number" to assert that e.id is a number
});
}
// if a collection wasn't in the collectionOrder, add it to the end
collections.forEach((collection) => {
if (
!account.collectionOrder.includes(collection.id as number) &&
(!collection.parentId || collection.ownerId !== account.id)
) {
updateAccount({
...account,
collectionOrder: [
...account.collectionOrder,
collection.id as number,
],
});
}
});
}, [router, collections, account]);
return (
@@ -31,6 +31,8 @@ export default async function deleteCollection(
},
});
await removeFromOrders(userId, collectionId);
return { response: deletedUsersAndCollectionsRelation, status: 200 };
} else if (collectionIsAccessible?.ownerId !== userId) {
return { response: "Collection is not accessible.", status: 401 };
@@ -57,6 +59,8 @@ export default async function deleteCollection(
await removeFolder({ filePath: `archives/${collectionId}` });
await removeFromOrders(userId, collectionId);
return await prisma.collection.delete({
where: {
id: collectionId,
@@ -98,3 +102,28 @@ async function deleteSubCollections(collectionId: number) {
await removeFolder({ filePath: `archives/${subCollection.id}` });
}
}
async function removeFromOrders(userId: number, collectionId: number) {
const userCollectionOrder = await prisma.user.findUnique({
where: {
id: userId,
},
select: {
collectionOrder: true,
},
});
if (userCollectionOrder)
await prisma.user.update({
where: {
id: userId,
},
data: {
collectionOrder: {
set: userCollectionOrder.collectionOrder.filter(
(e: number) => e !== collectionId
),
},
},
});
}
@@ -47,6 +47,17 @@ export default async function updateCollection(
},
});
await prisma.user.update({
where: {
id: userId,
},
data: {
collectionOrder: {
push: collectionId,
},
},
});
return await prisma.collection.update({
where: {
id: collectionId,