el.xwx.moe/lib/api/controllers/links/deleteLink.ts

43 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-04-23 08:26:39 -05:00
// Copyright (C) 2022-present Daniel31x13 <daniel31x13@gmail.com>
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
2023-03-23 10:25:17 -05:00
import { prisma } from "@/lib/api/db";
2023-03-25 09:17:34 -05:00
import { ExtendedLink } from "@/types/global";
import fs from "fs";
2023-03-23 10:25:17 -05:00
import { Link, UsersAndCollections } from "@prisma/client";
import hasAccessToCollection from "@/lib/api/hasAccessToCollection";
2023-03-28 02:31:50 -05:00
export default async function (link: ExtendedLink, userId: number) {
if (!link) return { response: "Please choose a valid link.", status: 401 };
2023-03-23 10:25:17 -05:00
const collectionIsAccessible = await hasAccessToCollection(
2023-03-28 02:31:50 -05:00
userId,
2023-03-23 10:25:17 -05:00
link.collectionId
);
const memberHasAccess = collectionIsAccessible?.members.some(
2023-03-28 02:31:50 -05:00
(e: UsersAndCollections) => e.userId === userId && e.canDelete
2023-03-23 10:25:17 -05:00
);
2023-03-28 02:31:50 -05:00
if (!(collectionIsAccessible?.ownerId === userId || memberHasAccess))
return { response: "Collection is not accessible.", status: 401 };
2023-03-23 10:25:17 -05:00
const deleteLink: Link = await prisma.link.delete({
where: {
id: link.id,
},
});
2023-03-25 09:17:34 -05:00
fs.unlink(`data/archives/${link.collectionId}/${link.id}.pdf`, (err) => {
if (err) console.log(err);
});
fs.unlink(`data/archives/${link.collectionId}/${link.id}.png`, (err) => {
if (err) console.log(err);
});
2023-03-28 02:31:50 -05:00
return { response: deleteLink, status: 200 };
2023-03-23 10:25:17 -05:00
}