mirror of
https://github.com/p-stream/backend.git
synced 2026-01-11 20:10:33 +00:00
72 lines
1.7 KiB
TypeScript
72 lines
1.7 KiB
TypeScript
import { useAuth } from "#imports";
|
|
import { PrismaClient } from "@prisma/client";
|
|
import { z } from "zod";
|
|
|
|
const prisma = new PrismaClient();
|
|
|
|
// Schema for validating the request body
|
|
const listItemSchema = z.object({
|
|
tmdb_id: z.string(),
|
|
});
|
|
|
|
const createListSchema = z.object({
|
|
name: z.string().min(1).max(255),
|
|
description: z.string().max(255).optional().nullable(),
|
|
items: z.array(listItemSchema).optional(),
|
|
});
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const userId = event.context.params?.id;
|
|
const session = await useAuth().getCurrentSession();
|
|
|
|
if (session.user !== userId) {
|
|
throw createError({
|
|
statusCode: 403,
|
|
message: "Cannot modify user other than yourself",
|
|
});
|
|
}
|
|
|
|
const body = await readBody(event);
|
|
|
|
let parsedBody;
|
|
try {
|
|
parsedBody = typeof body === "string" ? JSON.parse(body) : body;
|
|
} catch (error) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
message: "Invalid request body format",
|
|
});
|
|
}
|
|
|
|
const validatedBody = createListSchema.parse(parsedBody);
|
|
|
|
const result = await prisma.$transaction(async (tx) => {
|
|
const newList = await tx.lists.create({
|
|
data: {
|
|
user_id: userId,
|
|
name: validatedBody.name,
|
|
description: validatedBody.description || null,
|
|
},
|
|
});
|
|
|
|
if (validatedBody.items && validatedBody.items.length > 0) {
|
|
await tx.list_items.createMany({
|
|
data: validatedBody.items.map((item) => ({
|
|
list_id: newList.id,
|
|
tmdb_id: item.tmdb_id,
|
|
})),
|
|
skipDuplicates: true,
|
|
});
|
|
}
|
|
|
|
return tx.lists.findUnique({
|
|
where: { id: newList.id },
|
|
include: { list_items: true },
|
|
});
|
|
});
|
|
|
|
return {
|
|
list: result,
|
|
message: "List created successfully",
|
|
};
|
|
});
|