Skip to content

Commit

Permalink
feat: begin converting to next server actions for forms
Browse files Browse the repository at this point in the history
  • Loading branch information
ndom91 committed Dec 21, 2023
1 parent 8a23022 commit 1b22a14
Show file tree
Hide file tree
Showing 4 changed files with 156 additions and 105 deletions.
28 changes: 8 additions & 20 deletions src/app/api/categories/route.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,14 @@
import prisma from "@/lib/prisma"
import { auth } from "../../../../auth"

const verifyAuth = async () => {
const session = await auth()
console.log("AUTH.SESSION", session)
if (!session?.user?.userId) {
return Response(401)
}
}

export async function GET() {
await verifyAuth()

return Response("Hello World!", {
status: 200,
})
}

// export async function POST(request) {
export const POST = auth(async (request) => {
console.log("CATEGORIES.REQ.AUTH", request.auth)

const {
userId,
data: { name, description },
Expand All @@ -46,12 +34,12 @@ export const POST = auth(async (request) => {
return Response.json({ data: createResult })
})

export async function PUT(request) {
await verifyAuth()
export const PUT = auth(async (request) => {
const { userId, name, id, description } = await request.json()
console.log("PUT DATA", { userId, name, id, description })

if (!name || !id || !userId) {
return Response(
return new Response(
{ message: "Missing required field(s)" },
{
status: 400,
Expand All @@ -70,10 +58,10 @@ export async function PUT(request) {
})

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

export const DELETE = auth(async (request) => {
const { userId, id } = await request.json()

if (!id || !userId) {
return Response(
Expand All @@ -92,4 +80,4 @@ export async function DELETE(request) {
return Response({ message: error }, { status: 500 })
}
return Response.json({ message: "Deleted" })
}
})
80 changes: 75 additions & 5 deletions src/app/categories/actions.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const createCategory = async (userId, formData) => {
}

try {
const addRes = await fetch(`${protocol}${host}/api/categories`, {
const addResponse = await fetch(`${protocol}${host}/api/categories`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Expand All @@ -47,9 +47,9 @@ const createCategory = async (userId, formData) => {
userId,
}),
})
if (addRes.ok) {
revalidatePath("/posts")
return addRes.json()
if (addResponse.ok) {
revalidatePath("/categories")
return addResponse.json()
}
} catch (error) {
console.error(error)
Expand All @@ -59,4 +59,74 @@ const createCategory = async (userId, formData) => {
}
}

export { createCategory }
const deleteCategory = async (userId, id) => {
const headersList = headers()
const referer = headersList.get("referer")

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

try {
const deleteResponse = await fetch(`${protocol}${host}/api/categories`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
id,
userId,
}),
})
if (deleteResponse.ok) {
revalidatePath("/categories")
}
} catch (error) {
console.error(error)
}
}

const saveCategoryEdit = async ({ name, description, id, userId }) => {
const headersList = headers()
const referer = headersList.get("referer")

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

try {
if (name.length > 190 || description.length > 190) {
// toast(toastTypes.WARNING, "Category or name too long")
return
}
const editRes = await fetch(`${protocol}${host}/api/categories`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
id,
userId,
name,
description,
}),
})
console.log("EDIT RES", editRes.ok)
console.log("EDIT STATUS", editRes.status)
if (editRes.ok) {
return editRes.json()
// updateCategory(id, {
// name: categoryName,
// description: categoryDesc,
// })
// toggleEditMode()
// toast(toastTypes.SUCCESS, `Successfully edited "${name}"`)
} else {
return { errors: ["Could not save updated category!"] }
}
} catch (error) {
console.error(error)
return { message: error }
// toast(toastTypes.ERROR, `Error editing "${name}"`)
}
}

export { createCategory, deleteCategory, saveCategoryEdit }
40 changes: 32 additions & 8 deletions src/app/categories/categoryTable.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use client"

import { useState } from "react"
import { useEffect, useState } from "react"

import { SubmitButton } from "./submitButton"
import CategoryTableRow from "@/components/categoryTableRow"
Expand All @@ -20,9 +20,30 @@ const breadcrumbs = [
]

export default function CategoryTable({ categories, userId }) {
// const toast = useToast(5000)
const createCategoryWithUser = createCategory.bind(null, userId)
const [searchString, setSearchString] = useState("")
const toast = useToast(5000)
const [filteredCategories, setFilteredCategories] = useState(categories)

// Filter search results
useEffect(() => {
if (searchString) {
setFilteredCategories(
categories
.map((cat) => {
if (
cat.name.includes(searchString) ||
cat.description?.toLowerCase().includes(searchString.toLowerCase())
) {
return cat
}
})
.filter(Boolean),
)
} else {
setFilteredCategories(categories)
}
}, [searchString, categories])

return (
<>
Expand Down Expand Up @@ -52,6 +73,7 @@ export default function CategoryTable({ categories, userId }) {
<input
type="text"
id="table"
value={searchString}
onChange={(e) => setSearchString(e.target.value)}
className="w-2/3 rounded-md border-2 border-slate-200 px-2 py-1 pl-8 pr-8 text-base text-slate-600 outline-none placeholder:text-slate-200 focus:border-slate-200 focus:ring-2 focus:ring-slate-200 focus:ring-offset-transparent"
placeholder="Search for items"
Expand Down Expand Up @@ -85,8 +107,8 @@ export default function CategoryTable({ categories, userId }) {
</tr>
</thead>
<tbody>
{categories?.map((category) => (
<CategoryTableRow item={category} key={category.id} />
{filteredCategories?.map((category) => (
<CategoryTableRow item={category} key={category.id} userId={userId} />
))}
<tr className="bg-white even:bg-gray-50 hover:bg-slate-100">
<td className={`px-6 py-2`}>
Expand All @@ -97,22 +119,24 @@ export default function CategoryTable({ categories, userId }) {
<input
name="name"
type="text"
placeholder="Required"
placeholder="Name"
required
maxLength="190"
className="block w-full rounded-md border-2 border-slate-200 bg-slate-50 p-2 py-1 text-sm text-slate-900 placeholder-slate-300 focus:border-slate-500 focus:ring-slate-500 "
/>
</td>
<td className={`px-6 py-2`}>
<td className={`px-6 py-2`} colSpan="2">
<input
name="description"
type="text"
placeholder="Optional"
placeholder="Description"
maxLength="190"
className="block w-full rounded-md border-2 border-slate-200 bg-slate-50 px-2 py-1 text-sm text-slate-900 placeholder-slate-300 focus:border-slate-500 focus:ring-slate-500"
/>
</td>
<td className="px-6 py-4 text-right">
<SubmitButton action={createCategoryWithUser} />
</td>
<td className={`px-6 py-2`} />
</tr>
</tbody>
</table>
Expand Down
Loading

0 comments on commit 1b22a14

Please # to comment.