Files
link-free/src/pages/api/data.ts

63 lines
1.4 KiB
TypeScript
Raw Normal View History

2021-12-15 14:05:27 -03:00
import { Prisma } from '@prisma/client'
2021-12-15 08:11:58 -03:00
import type { NextApiRequest, NextApiResponse } from 'next'
2021-12-13 15:34:37 -03:00
import nc from 'next-connect'
import { prisma } from '../../services/prisma'
2021-12-15 14:05:27 -03:00
import { ExceptionError } from '../../utils/error'
2021-12-13 15:34:37 -03:00
2021-12-15 08:11:58 -03:00
const handler = nc<NextApiRequest, NextApiResponse>({
onNoMatch: (_req, res) => {
res.status(404).json({ error: 'Not found' })
},
onError: (err, _req, res) => {
2021-12-15 14:05:27 -03:00
if (err instanceof ExceptionError) {
res.status(err.status).json({
status: err.status,
error: err.message
})
} else if (err instanceof Prisma.PrismaClientKnownRequestError) {
res.status(400).json({
status: 400,
error: err.message
})
} else {
res.status(500).json({
status: 500,
error: err.message
})
}
2021-12-15 08:11:58 -03:00
}
})
2021-12-13 15:34:37 -03:00
.get(async (_req, res) => {
2021-12-15 08:11:58 -03:00
const response = await prisma.data.findUnique({
where: { id: 1 }
})
if (!response) {
2021-12-15 14:05:27 -03:00
throw new ExceptionError('No data found')
2021-12-13 15:34:37 -03:00
}
2021-12-15 08:11:58 -03:00
res.status(200).json(response?.data)
2021-12-13 15:34:37 -03:00
})
.put(async (req, res) => {
2021-12-15 08:11:58 -03:00
const { data } = req.body
if (!data) {
2021-12-15 14:05:27 -03:00
throw new ExceptionError('No data provided')
2021-12-15 08:11:58 -03:00
}
2021-12-13 15:34:37 -03:00
try {
const response = await prisma.data.update({
2021-12-15 08:11:58 -03:00
where: { id: 1 },
2021-12-13 15:34:37 -03:00
data: { data: JSON.stringify(req.body.data) }
})
res.status(200).json(response)
2021-12-15 08:11:58 -03:00
} catch (err: any) {
2021-12-15 14:05:27 -03:00
throw new ExceptionError(err)
2021-12-13 15:34:37 -03:00
}
})
export default handler