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

93 lines
2.5 KiB
TypeScript
Raw Normal View History

import { prisma } from "@/lib/api/db";
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import getTitle from "@/lib/api/getTitle";
import archive from "@/lib/api/archive";
2023-06-24 16:54:35 -05:00
import { Collection, Link, UsersAndCollections } from "@prisma/client";
import getPermission from "@/lib/api/getPermission";
2023-07-18 10:59:57 -05:00
import createFolder from "@/lib/api/storage/createFolder";
export default async function postLink(
link: LinkIncludingShortenedCollectionAndTags,
2023-05-27 11:29:39 -05:00
userId: number
) {
2023-03-28 02:31:50 -05:00
link.collection.name = link.collection.name.trim();
if (!link.name) {
2023-06-24 16:54:35 -05:00
return { response: "Please enter a valid name for the link.", status: 400 };
2023-03-28 02:31:50 -05:00
} else if (!link.collection.name) {
2023-07-18 10:59:57 -05:00
link.collection.name = "Other";
}
2023-05-27 11:29:39 -05:00
if (link.collection.id) {
2023-06-24 16:54:35 -05:00
const collectionIsAccessible = (await getPermission(
2023-03-28 02:31:50 -05:00
userId,
link.collection.id
2023-06-24 16:54:35 -05:00
)) as
| (Collection & {
members: UsersAndCollections[];
})
| null;
2023-03-28 02:31:50 -05:00
const memberHasAccess = collectionIsAccessible?.members.some(
(e: UsersAndCollections) => e.userId === userId && e.canCreate
);
2023-03-28 02:31:50 -05:00
if (!(collectionIsAccessible?.ownerId === userId || memberHasAccess))
return { response: "Collection is not accessible.", status: 401 };
} else {
link.collection.ownerId = userId;
}
const description =
link.description && link.description !== ""
? link.description
: await getTitle(link.url);
const newLink: Link = await prisma.link.create({
data: {
name: link.name,
2023-03-05 15:03:20 -06:00
url: link.url,
description,
collection: {
2023-03-28 02:31:50 -05:00
connectOrCreate: {
where: {
name_ownerId: {
ownerId: link.collection.ownerId,
name: link.collection.name,
},
},
create: {
name: link.collection.name,
ownerId: userId,
},
},
},
tags: {
2023-03-28 02:31:50 -05:00
connectOrCreate: link.tags.map((tag) => ({
where: {
2023-03-28 02:31:50 -05:00
name_ownerId: {
name: tag.name,
ownerId: link.collection.ownerId,
},
},
create: {
2023-03-28 02:31:50 -05:00
name: tag.name,
owner: {
connect: {
2023-03-28 02:31:50 -05:00
id: link.collection.ownerId,
},
},
},
})),
},
},
2023-03-10 13:25:33 -06:00
include: { tags: true, collection: true },
});
2023-07-18 10:59:57 -05:00
createFolder({ filePath: `archives/${newLink.collectionId}` });
2023-06-13 09:30:52 -05:00
archive(newLink.url, newLink.collectionId, newLink.id);
2023-06-13 09:30:52 -05:00
return { response: newLink, status: 200 };
}