Skip to content

Commit

Permalink
feat: fix api route and cache invalidation on categories
Browse files Browse the repository at this point in the history
  • Loading branch information
ndom91 committed Dec 17, 2023
1 parent 85ef1d9 commit 8a23022
Show file tree
Hide file tree
Showing 3 changed files with 98 additions and 67 deletions.
151 changes: 86 additions & 65 deletions src/app/api/categories/route.js
Original file line number Diff line number Diff line change
@@ -1,74 +1,95 @@
import prisma from "@/lib/prisma"
import { unstable_getServerSession } from "next-auth/next"
import { authOptions } from "../auth/[...nextauth]"
import { withSentry } from "@sentry/nextjs"
import { auth } from "../../../../auth"

export default withSentry(async function handler(req, res) {
const session = await unstable_getServerSession(req, res, authOptions)
const { method, body } = req

if (session) {
switch (method) {
case "POST": {
const { userId, name, desc } = body
if (!name) {
return res.status(400).json({ message: "Missing required field(s)" })
}
const verifyAuth = async () => {
const session = await auth()
console.log("AUTH.SESSION", session)
if (!session?.user?.userId) {
return Response(401)
}
}

const createResult = await prisma.category.create({
data: {
name,
description: desc,
userId,
},
})
export async function GET() {
await verifyAuth()

return res.status(200).json({ data: createResult })
}
case "PUT": {
const { id, userId, name, description } = body
if (!name || !id || !userId) {
return res.status(400).json({ message: "Missing required field(s)" })
}
return Response("Hello World!", {
status: 200,
})
}

const updateResult = await prisma.category.update({
where: {
id,
},
data: {
name,
description,
},
})
// export async function POST(request) {
export const POST = auth(async (request) => {
console.log("CATEGORIES.REQ.AUTH", request.auth)

return res.status(200).json({ data: updateResult })
}
case "GET": {
return res.status(200).json({ results: ["Hello", "World"] })
}
case "DELETE": {
const { id, userId } = body
const {
userId,
data: { name, description },
} = await request.json()

if (!id || !userId) {
return res.status(400).json({ message: "Missing required field(s)" })
}
try {
await prisma.category.delete({
where: { id },
})
} catch (error) {
console.error("ERR", error)
return res.status(500).json({ message: error })
}
return res.status(200).json({ message: "Deleted" })
}
default: {
res.setHeader("Allow", ["GET", "DELETE", "POST", "PUT"])
return res.status(405).end(`Method ${method} Not Allowed`)
}
}
} else {
console.error("ERR - Unauthorized attempt at /api/categories")
return res.status(403).end("Unauthorized")
if (!name) {
return Response(
{ message: "Missing required field!" },
{
status: 400,
},
)
}

const createResult = await prisma.category.create({
data: {
name,
description,
userId,
},
})

return Response.json({ data: createResult })
})

export async function PUT(request) {
await verifyAuth()
const { userId, name, id, description } = await request.json()

if (!name || !id || !userId) {
return Response(
{ message: "Missing required field(s)" },
{
status: 400,
},
)
}

const updateResult = await prisma.category.update({
where: {
id,
},
data: {
name,
description,
},
})

return Response.json({ data: updateResult })
}
export async function DELETE(request) {
await verifyAuth()
const { id, userId } = await request.json()

if (!id || !userId) {
return Response(
{ message: "Missing required field(s)" },
{
status: 400,
},
)
}

try {
await prisma.category.delete({
where: { id },
})
} catch (error) {
return Response({ message: error }, { status: 500 })
}
return Response.json({ message: "Deleted" })
}
11 changes: 10 additions & 1 deletion src/app/categories/actions.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"use server"

import { z } from "zod"
import { headers } from "next/headers"
import { revalidatePath } from "next/cache"

const schema = z.object({
name: z
Expand All @@ -16,6 +18,12 @@ const schema = z.object({
})

const createCategory = async (userId, formData) => {
const headersList = headers()
const referer = headersList.get("referer")

const host = new URL(referer).host
const protocol = new URL(referer).protocol

const validatedFields = schema.safeParse({
name: formData.get("name"),
description: formData.get("description"),
Expand All @@ -29,7 +37,7 @@ const createCategory = async (userId, formData) => {
}

try {
const addRes = await fetch("/api/categories", {
const addRes = await fetch(`${protocol}${host}/api/categories`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Expand All @@ -40,6 +48,7 @@ const createCategory = async (userId, formData) => {
}),
})
if (addRes.ok) {
revalidatePath("/posts")
return addRes.json()
}
} catch (error) {
Expand Down
3 changes: 2 additions & 1 deletion src/app/categories/submitButton.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
import { useFormStatus } from "react-dom"
import { LoadingSpinner } from "@/components/loadingSpinner"

export function SubmitButton() {
export function SubmitButton({ action }) {
const { pending } = useFormStatus()

return (
<button
type="submit"
formAction={action}
className="flex items-center justify-center space-x-1 rounded-md bg-slate-700 px-2 py-1 pr-3 font-medium text-white outline-none"
aria-disabled={pending}
>
Expand Down

0 comments on commit 8a23022

Please sign in to comment.