2023-10-22 23:28:39 -05:00
|
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
2023-11-25 02:19:02 -06:00
|
|
|
import urlHandler from "@/lib/api/urlHandler";
|
2023-10-28 04:57:53 -05:00
|
|
|
import { prisma } from "@/lib/api/db";
|
2023-11-06 07:25:57 -06:00
|
|
|
import verifyUser from "@/lib/api/verifyUser";
|
2023-10-22 23:28:39 -05:00
|
|
|
|
2023-10-31 14:44:58 -05:00
|
|
|
const RE_ARCHIVE_LIMIT = Number(process.env.RE_ARCHIVE_LIMIT) || 5;
|
|
|
|
|
2023-10-22 23:28:39 -05:00
|
|
|
export default async function links(req: NextApiRequest, res: NextApiResponse) {
|
2023-11-06 07:25:57 -06:00
|
|
|
const user = await verifyUser({ req, res });
|
|
|
|
if (!user) return;
|
2023-10-22 23:28:39 -05:00
|
|
|
|
2023-10-28 04:57:53 -05:00
|
|
|
const link = await prisma.link.findUnique({
|
|
|
|
where: {
|
|
|
|
id: Number(req.query.id),
|
|
|
|
},
|
|
|
|
include: { collection: true },
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!link)
|
|
|
|
return res.status(404).json({
|
|
|
|
response: "Link not found.",
|
2023-10-22 23:28:39 -05:00
|
|
|
});
|
2023-10-28 04:57:53 -05:00
|
|
|
|
2023-11-02 13:59:31 -05:00
|
|
|
if (link.collection.ownerId !== user.id)
|
2023-10-28 04:57:53 -05:00
|
|
|
return res.status(401).json({
|
|
|
|
response: "Permission denied.",
|
|
|
|
});
|
|
|
|
|
|
|
|
if (req.method === "PUT") {
|
2023-10-31 14:44:58 -05:00
|
|
|
if (
|
|
|
|
link?.lastPreserved &&
|
|
|
|
getTimezoneDifferenceInMinutes(new Date(), link?.lastPreserved) <
|
|
|
|
RE_ARCHIVE_LIMIT
|
|
|
|
)
|
|
|
|
return res.status(400).json({
|
|
|
|
response: `This link is currently being saved or has already been preserved. Please retry in ${
|
|
|
|
RE_ARCHIVE_LIMIT -
|
|
|
|
Math.floor(
|
|
|
|
getTimezoneDifferenceInMinutes(new Date(), link?.lastPreserved)
|
|
|
|
)
|
|
|
|
} minutes or create a new one.`,
|
|
|
|
});
|
|
|
|
|
2023-11-25 02:19:02 -06:00
|
|
|
urlHandler(link.id, link.url, user.id);
|
2023-10-28 04:57:53 -05:00
|
|
|
return res.status(200).json({
|
|
|
|
response: "Link is being archived.",
|
2023-10-22 23:28:39 -05:00
|
|
|
});
|
|
|
|
}
|
2023-10-28 04:57:53 -05:00
|
|
|
|
2023-11-06 09:01:39 -06:00
|
|
|
// TODO - Later?
|
2023-10-28 04:57:53 -05:00
|
|
|
// else if (req.method === "DELETE") {}
|
2023-10-22 23:28:39 -05:00
|
|
|
}
|
2023-10-31 14:44:58 -05:00
|
|
|
|
|
|
|
const getTimezoneDifferenceInMinutes = (future: Date, past: Date) => {
|
|
|
|
const date1 = new Date(future);
|
|
|
|
const date2 = new Date(past);
|
|
|
|
|
|
|
|
const diffInMilliseconds = Math.abs(date1.getTime() - date2.getTime());
|
|
|
|
|
|
|
|
const diffInMinutes = diffInMilliseconds / (1000 * 60);
|
|
|
|
|
|
|
|
return diffInMinutes;
|
|
|
|
};
|