portfolio/pages/api/views/[slug].ts

47 lines
1.4 KiB
TypeScript

import type {NextApiRequest, NextApiResponse} from 'next'
import {prisma} from '@/lib/prisma'
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
if (req.query.slug !== undefined) {
const slug: string = req.query.slug.toString()
if (req.method === 'POST') {
const newOrUpdatedViews = await prisma.views.upsert({
where: {slug},
create: {
slug
},
update: {
count: {
increment: 1
}
}
})
return res.status(200).json({
views: newOrUpdatedViews.count.toString()
})
}
if (req.method === 'GET') {
const views = await prisma.views.findUnique({
where: {
slug
}
})
let count = null
if (views !== null) {
count = views.count.toString()
}
return res.status(200).json({
views: count
});
}
}
} catch (e: any) {
return res.status(500).json({message: e.message})
}
}