115 lines
2.5 KiB
TypeScript
115 lines
2.5 KiB
TypeScript
"use server"
|
|
import { prepGenreData, prepPubData, prepStoryData } from "./validate"
|
|
import { Genre, Pub, Story, Sub } from "@prisma/client"
|
|
import prisma from "./db"
|
|
import { revalidatePath } from "next/cache"
|
|
import { redirect } from "next/navigation"
|
|
import { storySchema, subSchema } from "app/ui/forms/schemas"
|
|
import { z } from "zod"
|
|
|
|
|
|
export async function updateField({ datum, table, column, id, pathname }: { datum?: string | number | Genre[], table: string, column: string, id: number, pathname: string }) {
|
|
"use server"
|
|
try {
|
|
const res = await prisma[table].update({
|
|
where: { id },
|
|
data: {
|
|
[column]: datum
|
|
}
|
|
})
|
|
console.log(`updated record in ${table}: ${JSON.stringify(res)}`)
|
|
revalidatePath(pathname)
|
|
return res
|
|
} catch (error) {
|
|
console.error(error)
|
|
return false
|
|
}
|
|
}
|
|
|
|
export async function updateGenres({ genres, table, id, pathname }: { genres: { id: number }[], table: string, id: number, pathname: string }) {
|
|
"use server"
|
|
try {
|
|
const res = await prisma[table].update({
|
|
where: { id },
|
|
data: {
|
|
genres: { set: genres }
|
|
}
|
|
})
|
|
console.log(`updated record in ${table}: ${JSON.stringify(res)}`)
|
|
revalidatePath(pathname)
|
|
return res
|
|
} catch (error) {
|
|
console.error(error)
|
|
return false
|
|
}
|
|
}
|
|
|
|
export async function updateSub(data: Sub): Promise<Sub | boolean> {
|
|
"use server"
|
|
try {
|
|
subSchema.parse(data)
|
|
const res = await prisma.sub.update({ where: { id: data.id }, data })
|
|
revalidatePath("submission")
|
|
return res
|
|
} catch (error) {
|
|
console.error(error)
|
|
return false
|
|
}
|
|
}
|
|
|
|
|
|
export async function updateStory(data: Story & { genres: number[] }): Promise<Story | boolean> {
|
|
"use server"
|
|
|
|
try {
|
|
//prep and validate
|
|
const storyData = await prepStoryData(data)
|
|
const genresArray = await prepGenreData(data.genres)
|
|
//submit
|
|
const res = prisma.story.update({
|
|
where: { id: data.id },
|
|
data: storyData
|
|
})
|
|
await prisma.story.update({
|
|
where: { id: data.id },
|
|
data: {
|
|
genres: { set: genresArray }
|
|
}
|
|
})
|
|
return res
|
|
} catch (error) {
|
|
console.error(error)
|
|
return false
|
|
}
|
|
}
|
|
|
|
|
|
export async function updatePub(data: Pub & { genres: number[] }): Promise<Pub | boolean> {
|
|
"use server"
|
|
|
|
try {
|
|
//prep and validate
|
|
const pubData = await prepPubData
|
|
(data)
|
|
const genresArray = await prepGenreData(data.genres)
|
|
//submit
|
|
const res = prisma.pub.update({
|
|
where: { id: data.id },
|
|
data: pubData
|
|
})
|
|
await prisma.pub.update({
|
|
where: { id: data.id },
|
|
data: {
|
|
genres: { set: genresArray }
|
|
}
|
|
})
|
|
return res
|
|
} catch (error) {
|
|
console.error(error)
|
|
return false
|
|
}
|
|
}
|
|
|
|
|
|
|