import { and, eq, gte, sql } from 'drizzle-orm' import { z } from 'zod' const schema = z.object({ title: z.string().default(''), synopsis: z.string().default(''), /** 插入位置;不传则追加到末尾 */ index: z.number().int().positive().optional() }) export default defineEventHandler(async (event) => { const projectId = param(event) getProject(projectId) const body = await readJson(event, schema) const db = useDb() const max = db.select({ m: sql`coalesce(max(${tables.chapters.index}), 0)` }).from(tables.chapters).where(eq(tables.chapters.projectId, projectId)).get()?.m ?? 0 const index = body.index && body.index <= max ? body.index : max + 1 const row = db.transaction((tx) => { if (index <= max) { tx.update(tables.chapters).set({ index: sql`${tables.chapters.index} + 1` }) .where(and(eq(tables.chapters.projectId, projectId), gte(tables.chapters.index, index))).run() } return tx.insert(tables.chapters).values({ id: newId(), projectId, index, title: body.title, synopsis: body.synopsis }).returning().get() }) emitProject(projectId, { type: 'chapters' }) return row })