1
Fork 0
mirror of https://github.com/Steffo99/festa.git synced 2024-12-23 15:14:23 +00:00
festa/pages/api/events/[slug].ts

42 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-05-31 03:03:48 +00:00
import { client } from "../../../utils/prismaClient";
2022-05-30 03:19:49 +00:00
import { NextApiRequest, NextApiResponse } from "next";
import { ApiResult } from "../../../types/api";
2022-05-31 10:00:55 +00:00
import { Model, restInPeace } from "../../../utils/restInPeace";
2022-05-31 03:03:48 +00:00
import { default as cryptoRandomString} from "crypto-random-string";
2022-05-31 10:00:55 +00:00
import { handleInterrupts, Interrupt } from "../../../utils/interrupt";
2022-05-31 03:03:48 +00:00
import { authorizeUser } from "../../../utils/apiAuth";
2022-05-31 10:00:55 +00:00
import { Event } from "@prisma/client";
2022-05-31 03:03:48 +00:00
2022-05-30 03:19:49 +00:00
export default async function handler(req: NextApiRequest, res: NextApiResponse<ApiResult<Event | Event[]>>) {
2022-05-31 03:03:48 +00:00
handleInterrupts(res, async () => {
const user = await authorizeUser(req, res)
2022-05-31 14:01:34 +00:00
const canEdit = async (_model: Model, obj?: Event) => {
2022-05-31 10:00:55 +00:00
if(obj && obj.creatorId !== user.id) {
throw new Interrupt(403, {error: "Only the creator can edit an event"})
}
}
2022-05-31 03:03:48 +00:00
const which = {
slug: req.query.slug
}
const create = {
slug: cryptoRandomString({length: 12, type: "url-safe"}),
creatorId: user.id,
name: req.body.name
}
const update = {
name: req.body.name
}
2022-05-31 10:06:37 +00:00
await restInPeace(req, res, {
2022-05-31 03:03:48 +00:00
model: client.event,
retrieve: {which},
create: {create},
upsert: {which, create, update, before: canEdit},
update: {which, update, before: canEdit},
destroy: {which, before: canEdit},
2022-05-31 03:03:48 +00:00
})
2022-05-30 03:19:49 +00:00
})
}