el.xwx.moe/lib/api/controllers/collections/postCollection.ts

73 lines
2.2 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-02-18 21:32:02 -06:00
import { prisma } from "@/lib/api/db";
import { NewCollection } from "@/types/global";
import { existsSync, mkdirSync } from "fs";
2023-02-08 15:11:33 -06:00
export default async function (collection: NewCollection, userId: number) {
2023-04-25 07:39:46 -05:00
if (!collection || collection.name.trim() === "")
2023-03-28 02:31:50 -05:00
return {
2023-04-24 16:30:40 -05:00
response: "Please enter a valid collection.",
2023-03-28 02:31:50 -05:00
status: 400,
};
2023-02-08 15:11:33 -06:00
2023-03-28 02:31:50 -05:00
const findCollection = await prisma.user.findUnique({
2023-02-08 15:11:33 -06:00
where: {
2023-03-28 02:31:50 -05:00
id: userId,
2023-02-08 15:11:33 -06:00
},
select: {
2023-02-08 15:11:33 -06:00
collections: {
where: {
2023-04-24 16:30:40 -05:00
name: collection.name,
2023-02-08 15:11:33 -06:00
},
},
},
});
const checkIfCollectionExists = findCollection?.collections[0];
2023-03-28 02:31:50 -05:00
if (checkIfCollectionExists)
return { response: "Collection already exists.", status: 400 };
2023-02-08 15:11:33 -06:00
const newCollection = await prisma.collection.create({
2023-02-08 15:11:33 -06:00
data: {
2023-02-18 21:32:02 -06:00
owner: {
connect: {
2023-03-28 02:31:50 -05:00
id: userId,
2023-02-18 21:32:02 -06:00
},
2023-02-08 15:11:33 -06:00
},
2023-04-24 16:30:40 -05:00
name: collection.name,
description: collection.description,
members: {
create: collection.members.map((e) => ({
user: { connect: { email: e.email } },
canCreate: e.canCreate,
canUpdate: e.canUpdate,
canDelete: e.canDelete,
})),
},
2023-02-08 15:11:33 -06:00
},
2023-05-01 15:00:23 -05:00
include: {
members: {
include: {
user: {
select: {
email: true,
name: true,
},
},
},
},
},
2023-02-08 15:11:33 -06:00
});
const collectionPath = `data/archives/${newCollection.id}`;
if (!existsSync(collectionPath))
mkdirSync(collectionPath, { recursive: true });
2023-03-28 02:31:50 -05:00
return { response: newCollection, status: 200 };
2023-02-08 15:11:33 -06:00
}