ff98547dbb
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
94 lines
2.6 KiB
TypeScript
94 lines
2.6 KiB
TypeScript
import { z } from "zod";
|
|
import { createRouter, publicQuery, adminQuery } from "./middleware";
|
|
import { getDb } from "./queries/connection";
|
|
import { documents } from "@db/schema";
|
|
import { eq, desc } from "drizzle-orm";
|
|
|
|
export const documentsRouter = createRouter({
|
|
list: publicQuery.query(async () => {
|
|
const db = getDb();
|
|
return db
|
|
.select()
|
|
.from(documents)
|
|
.where(eq(documents.published, "published"))
|
|
.orderBy(desc(documents.createdAt));
|
|
}),
|
|
|
|
listAll: adminQuery.query(async () => {
|
|
const db = getDb();
|
|
return db
|
|
.select()
|
|
.from(documents)
|
|
.orderBy(desc(documents.createdAt));
|
|
}),
|
|
|
|
getBySlug: publicQuery
|
|
.input(z.object({ slug: z.string() }))
|
|
.query(async ({ input }) => {
|
|
const db = getDb();
|
|
const results = await db
|
|
.select()
|
|
.from(documents)
|
|
.where(eq(documents.slug, input.slug))
|
|
.limit(1);
|
|
return results[0] ?? null;
|
|
}),
|
|
|
|
create: adminQuery
|
|
.input(
|
|
z.object({
|
|
title: z.string().min(1).max(255),
|
|
slug: z.string().min(1).max(255),
|
|
excerpt: z.string().optional(),
|
|
content: z.string().min(1),
|
|
coverImage: z.string().optional(),
|
|
tags: z.string().optional(),
|
|
published: z.enum(["draft", "published"]).default("published"),
|
|
})
|
|
)
|
|
.mutation(async ({ input }) => {
|
|
const db = getDb();
|
|
const result = await db.insert(documents).values({
|
|
title: input.title,
|
|
slug: input.slug,
|
|
excerpt: input.excerpt ?? "",
|
|
content: input.content,
|
|
coverImage: input.coverImage ?? "",
|
|
tags: input.tags ?? "",
|
|
published: input.published,
|
|
});
|
|
return { id: Number(result[0].insertId) };
|
|
}),
|
|
|
|
update: adminQuery
|
|
.input(
|
|
z.object({
|
|
id: z.number(),
|
|
title: z.string().min(1).max(255).optional(),
|
|
slug: z.string().min(1).max(255).optional(),
|
|
excerpt: z.string().optional(),
|
|
content: z.string().optional(),
|
|
coverImage: z.string().optional(),
|
|
tags: z.string().optional(),
|
|
published: z.enum(["draft", "published"]).optional(),
|
|
})
|
|
)
|
|
.mutation(async ({ input }) => {
|
|
const db = getDb();
|
|
const { id, ...data } = input;
|
|
await db
|
|
.update(documents)
|
|
.set(data)
|
|
.where(eq(documents.id, id));
|
|
return { success: true };
|
|
}),
|
|
|
|
delete: adminQuery
|
|
.input(z.object({ id: z.number() }))
|
|
.mutation(async ({ input }) => {
|
|
const db = getDb();
|
|
await db.delete(documents).where(eq(documents.id, input.id));
|
|
return { success: true };
|
|
}),
|
|
});
|