enzostvs's picture
enzostvs HF staff
gallery viewer
f05d33c
raw
history blame
1.79 kB
import { json, type RequestEvent } from '@sveltejs/kit';
import { tokenIsAvailable } from '$lib/utils';
import prisma from '$lib/prisma';
/** @type {import('./$types').RequestHandler} */
export async function POST({ cookies, request, params } : RequestEvent) {
const id = params.id?.replace("@", "/")
const model = await prisma.model.findFirst({
where: {
id,
},
})
if (!model) {
return json({
error: "Model not found",
}, { status: 404 })
}
const token = cookies.get('hf_access_token')
if (!token) {
return json({
error: "You must be logged",
}, { status: 401 })
}
const is_token_available = await tokenIsAvailable(token)
if (!is_token_available) {
return json({
error: "Invalid token",
}, { status: 401 })
}
// check if user has already comment this model twice
const total_comments = await prisma.comment.count({
where: {
modelId: model.id,
userId: is_token_available.sub,
}
})
if (total_comments >= 2) {
return json({
error: "You have already comment this model twice",
}, { status: 401 })
}
const { text } = await request.json()
if (!text || text.length < 3) {
return json({
error: "Text must be at least 10 characters",
}, { status: 400 })
}
const comment = await prisma.comment.create({
data: {
text,
user: {
connect: {
sub: is_token_available.sub
}
},
model: {
connect: {
id
}
}
},
select: {
id: true,
text: true,
createdAt: true,
user: {
select: {
name: true,
picture: true,
sub: true,
}
}
}
})
return json({
success: true,
comment
})
}