81 lines
1.9 KiB
TypeScript
81 lines
1.9 KiB
TypeScript
"use server"
|
|
import { Pub, Story, Sub } from "@prisma/client"
|
|
import prisma from "./db"
|
|
import { revalidatePath } from "next/cache"
|
|
import { z } from "zod"
|
|
import { pubSchema } from "app/ui/forms/schemas"
|
|
import { subSchema } from "app/ui/forms/schemas"
|
|
import { prepGenreData, prepStoryData } from "./validate"
|
|
|
|
|
|
export async function createStory({ story, genres }: { story: Story, genres: number[] }): Promise<{ success: string }> {
|
|
// will return undefined if middleware authorization fails
|
|
"use server"
|
|
try {
|
|
const storyData = await prepStoryData(story)
|
|
const genresArray = await prepGenreData(genres)
|
|
|
|
//submit
|
|
const res = await prisma.story.create({ data: storyData })
|
|
await prisma.story.update({
|
|
where: { id: res.id },
|
|
data: {
|
|
genres: { set: genresArray }
|
|
}
|
|
})
|
|
revalidatePath("/story")
|
|
return { success: `Created the story '${story.title}'.` }
|
|
} catch (error) {
|
|
console.error(error)
|
|
}
|
|
|
|
}
|
|
|
|
|
|
export async function createPub({ pub, genres }: { pub: Pub, genres: number[] }): Promise<{ success: string }> {
|
|
"use server"
|
|
const genresArray = genres.map(e => { return { id: e } })
|
|
|
|
//prepare schemas
|
|
const schema = pubSchema.omit({ genres: true })
|
|
const genreSchema = z.object({ id: z.number() })
|
|
const genresSchema = z.array(genreSchema)
|
|
|
|
try {
|
|
|
|
//validate
|
|
schema.parse(pub)
|
|
genresSchema.safeParse(genresArray)
|
|
|
|
//submit
|
|
const res = await prisma.pub.create({
|
|
data: pub
|
|
})
|
|
const genresRes = await prisma.pub.update({
|
|
where: { id: res.id },
|
|
data:
|
|
{ genres: { set: genresArray } }
|
|
})
|
|
revalidatePath("/publication")
|
|
return { success: `Created the publication '${pub.title}'.` }
|
|
} catch (error) {
|
|
console.error(error)
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function createSub(data: Sub): Promise<Sub | boolean> {
|
|
"use server"
|
|
try {
|
|
subSchema.parse(data)
|
|
const res = await prisma.sub.create({ data })
|
|
revalidatePath("/submission")
|
|
return res
|
|
} catch (error) {
|
|
console.error(error)
|
|
return false
|
|
}
|
|
}
|