subman-nextjs/src/app/lib/create.ts

81 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-06-26 16:18:44 +00:00
"use server"
2024-09-30 14:06:52 +00:00
import { Pub, Story, Sub } from "@prisma/client"
2024-06-26 16:18:44 +00:00
import prisma from "./db"
import { revalidatePath } from "next/cache"
2024-09-18 09:56:08 +00:00
import { z } from "zod"
2024-09-19 09:37:01 +00:00
import { pubSchema } from "app/ui/forms/schemas"
import { subSchema } from "app/ui/forms/schemas"
2024-09-25 10:23:16 +00:00
import { prepGenreData, prepStoryData } from "./validate"
2024-06-26 16:18:44 +00:00
2024-09-18 09:56:08 +00:00
2024-09-30 12:44:47 +00:00
export async function createStory({ story, genres }: { story: Story, genres: number[] }): Promise<{ success: string }> {
2024-09-18 09:56:08 +00:00
// will return undefined if middleware authorization fails
2024-06-26 16:18:44 +00:00
"use server"
2024-09-18 09:56:08 +00:00
try {
2024-09-30 12:44:47 +00:00
const storyData = await prepStoryData(story)
const genresArray = await prepGenreData(genres)
2024-09-19 09:37:01 +00:00
//submit
2024-09-18 09:56:08 +00:00
const res = await prisma.story.create({ data: storyData })
await prisma.story.update({
where: { id: res.id },
data: {
genres: { set: genresArray }
}
})
2024-09-19 09:37:01 +00:00
revalidatePath("/story")
2024-09-30 12:44:47 +00:00
return { success: `Created the story '${story.title}'.` }
2024-09-18 09:56:08 +00:00
} catch (error) {
2024-09-19 09:37:01 +00:00
console.error(error)
2024-09-18 09:56:08 +00:00
}
2024-09-25 10:23:16 +00:00
2024-06-26 16:18:44 +00:00
}
2024-09-30 12:44:47 +00:00
export async function createPub({ pub, genres }: { pub: Pub, genres: number[] }): Promise<{ success: string }> {
2024-06-26 17:32:18 +00:00
"use server"
2024-09-30 12:44:47 +00:00
const genresArray = genres.map(e => { return { id: e } })
2024-09-19 09:37:01 +00:00
//prepare schemas
const schema = pubSchema.omit({ genres: true })
const genreSchema = z.object({ id: z.number() })
const genresSchema = z.array(genreSchema)
try {
//validate
2024-09-30 12:44:47 +00:00
schema.parse(pub)
2024-09-19 09:37:01 +00:00
genresSchema.safeParse(genresArray)
//submit
const res = await prisma.pub.create({
2024-09-30 12:44:47 +00:00
data: pub
2024-09-19 09:37:01 +00:00
})
const genresRes = await prisma.pub.update({
where: { id: res.id },
data:
{ genres: { set: genresArray } }
})
revalidatePath("/publication")
2024-09-30 12:44:47 +00:00
return { success: `Created the publication '${pub.title}'.` }
2024-09-19 09:37:01 +00:00
} catch (error) {
console.error(error)
}
2024-06-26 17:32:18 +00:00
}
2024-06-26 16:18:44 +00:00
export async function createSub(data: Sub): Promise<Sub | boolean> {
"use server"
2024-09-19 09:37:01 +00:00
try {
subSchema.parse(data)
const res = await prisma.sub.create({ data })
revalidatePath("/submission")
return res
} catch (error) {
console.error(error)
return false
2024-09-19 09:37:01 +00:00
}
}