init
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
createTRPCRouter,
|
||||
protectedProcedure,
|
||||
publicProcedure,
|
||||
} from "@/server/api/trpc";
|
||||
import { categories } from "@/server/db/schema";
|
||||
|
||||
import { eq } from "drizzle-orm";
|
||||
import { hasPermission, Role } from "@/lib/validation/has-permission";
|
||||
import { categorySchema } from "@/lib/validation/zod/category";
|
||||
import { generateSlug } from "@/lib/utils";
|
||||
|
||||
export const categoryRouter = createTRPCRouter({
|
||||
get: publicProcedure
|
||||
.input(z.object({ slug: z.string() }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
return await ctx.db.query.categories.findFirst({
|
||||
where: eq(categories.slug, input.slug),
|
||||
});
|
||||
}),
|
||||
|
||||
getAll: publicProcedure.query(async ({ ctx }) => {
|
||||
return await ctx.db.query.categories.findMany();
|
||||
}),
|
||||
|
||||
create: protectedProcedure
|
||||
.input(z.object({ category: categorySchema }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const isEditor = hasPermission(ctx.session.user.role, Role.EDITOR);
|
||||
if (!isEditor) {
|
||||
throw new Error("You are not allowed to create categories");
|
||||
}
|
||||
const slug = generateSlug(input.category.name);
|
||||
return await ctx.db
|
||||
.insert(categories)
|
||||
.values({ ...input.category, slug })
|
||||
.returning({
|
||||
slug: categories.slug,
|
||||
});
|
||||
}),
|
||||
update: protectedProcedure
|
||||
.input(z.object({ category: categorySchema, categoryId: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const isEditor = hasPermission(ctx.session.user.role, Role.EDITOR);
|
||||
if (!isEditor) {
|
||||
throw new Error("You are not allowed to update categories");
|
||||
}
|
||||
return await ctx.db
|
||||
.update(categories)
|
||||
.set(input.category)
|
||||
.where(eq(categories.id, input.categoryId))
|
||||
.returning({
|
||||
id: categories.id,
|
||||
});
|
||||
}),
|
||||
delete: protectedProcedure
|
||||
.input(z.object({ categoryId: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const isEditor = hasPermission(ctx.session.user.role, Role.EDITOR);
|
||||
if (!isEditor) {
|
||||
throw new Error("You are not allowed to delete articles");
|
||||
}
|
||||
return await ctx.db
|
||||
.delete(categories)
|
||||
.where(eq(categories.id, input.categoryId))
|
||||
.returning({
|
||||
id: categories.id,
|
||||
});
|
||||
}),
|
||||
});
|
||||
Reference in New Issue
Block a user