el.xwx.moe/lib/api/controllers/migration/importFromLinkwarden.ts

93 lines
2.5 KiB
TypeScript
Raw Normal View History

2023-10-16 17:27:04 -05:00
import { prisma } from "@/lib/api/db";
import { Backup } from "@/types/global";
import createFolder from "@/lib/api/storage/createFolder";
export default async function getData(userId: number, rawData: string) {
const data: Backup = JSON.parse(rawData);
2023-11-07 07:03:35 -06:00
await prisma
.$transaction(
async () => {
// Import collections
for (const e of data.collections) {
e.name = e.name.trim();
2023-10-16 17:27:04 -05:00
2023-11-07 07:03:35 -06:00
const findCollection = await prisma.user.findUnique({
2023-10-16 17:27:04 -05:00
where: {
2023-11-07 07:03:35 -06:00
id: userId,
},
select: {
collections: {
where: {
name: e.name,
},
},
2023-10-16 17:27:04 -05:00
},
2023-11-07 07:03:35 -06:00
});
2023-10-16 17:27:04 -05:00
2023-11-07 07:03:35 -06:00
const checkIfCollectionExists = findCollection?.collections[0];
2023-10-16 17:27:04 -05:00
2023-11-07 07:03:35 -06:00
let collectionId = findCollection?.collections[0]?.id;
2023-10-16 17:27:04 -05:00
2023-11-07 07:03:35 -06:00
if (!checkIfCollectionExists) {
const newCollection = await prisma.collection.create({
data: {
owner: {
connect: {
id: userId,
},
},
name: e.name,
description: e.description,
color: e.color,
2023-10-16 17:27:04 -05:00
},
2023-11-07 07:03:35 -06:00
});
2023-10-16 17:27:04 -05:00
2023-11-07 07:03:35 -06:00
createFolder({ filePath: `archives/${newCollection.id}` });
2023-10-16 17:27:04 -05:00
2023-11-07 07:03:35 -06:00
collectionId = newCollection.id;
}
2023-10-16 17:27:04 -05:00
2023-11-07 07:03:35 -06:00
// Import Links
for (const link of e.links) {
const newLink = await prisma.link.create({
data: {
url: link.url,
name: link.name,
description: link.description,
collection: {
connect: {
id: collectionId,
2023-10-16 17:27:04 -05:00
},
},
2023-11-07 07:03:35 -06:00
// Import Tags
tags: {
connectOrCreate: link.tags.map((tag) => ({
where: {
name_ownerId: {
name: tag.name.trim(),
ownerId: userId,
},
2023-10-16 17:27:04 -05:00
},
2023-11-07 07:03:35 -06:00
create: {
name: tag.name.trim(),
owner: {
connect: {
id: userId,
},
},
},
})),
2023-10-16 17:27:04 -05:00
},
2023-11-07 07:03:35 -06:00
},
});
}
}
},
{ timeout: 30000 }
)
.catch((err) => console.log(err));
2023-10-16 17:27:04 -05:00
return { response: "Success.", status: 200 };
}