### Run Kirimase locally Source: https://github.com/nicoalbanese/kirimase/blob/master/README.md Commands to install dependencies, start the development environment, and install the package globally for local testing. ```sh pnpm i pnpm run dev npm install -g . (in a second terminal - this will then make kirimase available across your machine using "kirimase *command*") ``` -------------------------------- ### Kirimase Configuration File Structure Source: https://context7.com/nicoalbanese/kirimase/llms.txt Example structure of the kirimase.config.json file, which stores project settings and installed packages. ```json { "hasSrc": true, "preferredPackageManager": "pnpm", "driver": "pg", "provider": "neon", "packages": ["drizzle", "next-auth", "trpc", "shadcn-ui", "resend", "stripe"], "orm": "drizzle", "auth": "next-auth", "componentLib": "shadcn-ui", "t3": false, "alias": "@", "analytics": true } ``` -------------------------------- ### Install Kirimase CLI Source: https://github.com/nicoalbanese/kirimase/blob/master/README.md Install the Kirimase CLI globally using npm. This command is required before using Kirimase in your projects. ```bash npm install -g kirimase ``` -------------------------------- ### Next-Auth Route Handler Setup Source: https://context7.com/nicoalbanese/kirimase/llms.txt Sets up the Next-Auth API route handler for authentication. It uses the provided authOptions for configuration. ```typescript // Generated: app/api/auth/[...nextauth]/route.ts import NextAuth from "next-auth"; import { authOptions } from "@/lib/auth/utils"; const handler = NextAuth(authOptions); export { handler as GET, handler as POST }; ``` -------------------------------- ### Drizzle ORM with PostgreSQL Setup Source: https://context7.com/nicoalbanese/kirimase/llms.txt Initializes Drizzle ORM with a Neon PostgreSQL database connection. Requires DATABASE_URL environment variable. ```typescript // Generated: lib/db/index.ts import { drizzle } from "drizzle-orm/neon-http"; import { neon } from "@neondatabase/serverless"; import * as schema from "./schema"; const sql = neon(process.env.DATABASE_URL!); export const db = drizzle(sql, { schema }); ``` -------------------------------- ### Next-Auth Configuration Utilities Source: https://context7.com/nicoalbanese/kirimase/llms.txt Configures Next-Auth with Drizzle adapter, session callbacks, and OAuth providers (GitHub, Discord). Includes utility functions for getting user authentication status and checking authentication. ```typescript // Generated: lib/auth/utils.ts import { db } from "@/lib/db/index"; import { DrizzleAdapter } from "@auth/drizzle-adapter"; import { DefaultSession, getServerSession, NextAuthOptions } from "next-auth"; import GitHubProvider from "next-auth/providers/github"; import DiscordProvider from "next-auth/providers/discord"; declare module "next-auth" { interface Session { user: DefaultSession["user"] & { id: string; }; } } export type AuthSession = { session: { user: { id: string; name?: string; email?: string; }; } | null; }; export const authOptions: NextAuthOptions = { adapter: DrizzleAdapter(db), callbacks: { session: ({ session, user }) => { session.user.id = user.id; return session; }, }, providers: [ GitHubProvider({ clientId: process.env.GITHUB_CLIENT_ID!, clientSecret: process.env.GITHUB_CLIENT_SECRET!, }), DiscordProvider({ clientId: process.env.DISCORD_CLIENT_ID!, clientSecret: process.env.DISCORD_CLIENT_SECRET!, }), ], }; export const getUserAuth = async () => { const session = await getServerSession(authOptions); return { session } as AuthSession; }; export const checkAuth = async () => { const { session } = await getUserAuth(); if (!session) redirect("/api/auth/signin"); }; ``` -------------------------------- ### Drizzle ORM PostgreSQL Computer Schema Example Source: https://context7.com/nicoalbanese/kirimase/llms.txt Defines the 'computers' table schema for Drizzle ORM with PostgreSQL, including validation schemas for API requests using Zod. Requires nanoid utility. ```typescript // Generated: lib/db/schema/computers.ts (example model) import { sql } from "drizzle-orm"; import { varchar, timestamp, pgTable } from "drizzle-orm/pg-core"; import { createInsertSchema, createSelectSchema } from "drizzle-zod"; import { z } from "zod"; import { nanoid } from "@/lib/utils"; export const computers = pgTable("computers", { id: varchar("id", { length: 191 }) .primaryKey() .$defaultFn(() => nanoid()), brand: varchar("brand", { length: 256 }).notNull(), cores: integer("cores").notNull(), createdAt: timestamp("created_at") .notNull() .default(sql`now()`), updatedAt: timestamp("updated_at") .notNull() .default(sql`now()`), }); // Schema for computers - used to validate API requests export const insertComputerSchema = createInsertSchema(computers); export const insertComputerParams = createInsertSchema(computers, { brand: z.coerce.string(), cores: z.coerce.number(), }).omit({ id: true, createdAt: true, updatedAt: true }); export const updateComputerSchema = createSelectSchema(computers); export const updateComputerParams = createSelectSchema(computers, { brand: z.coerce.string(), cores: z.coerce.number(), }).omit({ createdAt: true, updatedAt: true }); export const computerIdSchema = updateComputerSchema.pick({ id: true }); // Types for computers export type Computer = typeof computers.$inferSelect; export type NewComputer = z.infer; export type NewComputerParams = z.infer; export type UpdateComputerParams = z.infer; export type ComputerId = z.infer["id"]; ``` -------------------------------- ### CLI Command: kirimase init Source: https://github.com/nicoalbanese/kirimase/blob/master/README.md Initializes and configures a new project using the Kirimase CLI in non-interactive mode. ```APIDOC ## CLI Command: kirimase init ### Description Initializes and configures a new project. This command allows for full automation of the setup process by passing flags directly. ### Method CLI Command ### Parameters #### Options - **--headless** (-h) (string) - Optional - Initialize without any UI ('yes' or 'no') - **--src-folder** (-sf) (string) - Optional - Use a src folder ('yes' or 'no') - **--package-manager** (-pm) (string) - Optional - Specify package manager - **--component-lib** (-cl) (string) - Optional - Specify component library - **--orm** (-o) (string) - Optional - Specify ORM - **--db** (-db) (string) - Optional - Specify database ('pg', 'mysql', 'sqlite') - **--db-provider** (-dbp) (string) - Optional - Specify database provider - **--auth** (-a) (string) - Optional - Specify authentication method - **--auth-providers** (-ap) (string) - Optional - Specify auth providers - **--misc-packages** (-mp) (string) - Optional - Specify additional packages ('trpc', 'shadcn-ui', 'resend') - **--include-example** (-ie) (string) - Optional - Include example ('yes' or 'no') ### Request Example kirimase init -sf yes -pm bun --orm prisma -db pg -a next-auth -ap github discord -mp trpc stripe resend -cl shadcn-ui -ie yes ``` -------------------------------- ### Initialize Kirimase Project Source: https://github.com/nicoalbanese/kirimase/blob/master/README.md Run this command within your Next.js project directory to initialize Kirimase. Note that Kirimase is not compatible with the pages directory. ```bash kirimase init ``` -------------------------------- ### Initialize Kirimase in a Project Source: https://context7.com/nicoalbanese/kirimase/llms.txt Initializes Kirimase within an existing Next.js project directory. Navigate to your project first. ```bash # Navigate to your Next.js project cd my-nextjs-app # Run initialization kirimase init ``` -------------------------------- ### Initialize Stripe Client Source: https://context7.com/nicoalbanese/kirimase/llms.txt Configures the Stripe SDK instance using the environment secret key. ```typescript // Generated: lib/stripe/index.ts import Stripe from "stripe"; export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, { apiVersion: "2023-10-16", typescript: true, }); ``` -------------------------------- ### Initialize Kirimase in non-interactive mode Source: https://github.com/nicoalbanese/kirimase/blob/master/README.md Run the initialization command with flags to bypass the interactive UI prompts. ```sh kirimase init -sf yes -pm bun --orm prisma -db pg -a next-auth -ap github discord -mp trpc stripe resend -cl shadcn-ui -ie yes ``` -------------------------------- ### Add Packages with Kirimase Source: https://github.com/nicoalbanese/kirimase/blob/master/README.md Use the 'kirimase add' command to initialize and configure various packages for your Next.js project. This includes ORMs, authentication solutions, and other utilities. ```bash kirimase add ``` -------------------------------- ### Configure tRPC Client Source: https://context7.com/nicoalbanese/kirimase/llms.txt Sets up the React Query-based tRPC client for the frontend. ```typescript // Generated: lib/trpc/client.ts import { createTRPCReact } from "@trpc/react-query"; import type { AppRouter } from "@/lib/server/routers/_app"; export const trpc = createTRPCReact(); ``` -------------------------------- ### Initialize tRPC Server Context and Procedures Source: https://context7.com/nicoalbanese/kirimase/llms.txt Configures the tRPC server instance, context, and middleware for protected procedures. ```typescript // Generated: lib/server/trpc.ts import { initTRPC, TRPCError } from "@trpc/server"; import superjson from "superjson"; import { ZodError } from "zod"; import { getServerSession } from "next-auth"; import { authOptions } from "@/lib/auth/utils"; export const createTRPCContext = async (opts: { headers: Headers }) => { const session = await getServerSession(authOptions); return { session, ...opts, }; }; const t = initTRPC.context().create({ transformer: superjson, errorFormatter({ shape, error }) { return { ...shape, data: { ...shape.data, zodError: error.cause instanceof ZodError ? error.cause.flatten() : null, }, }; }, }); export const router = t.router; export const publicProcedure = t.procedure; const enforceUserIsAuthed = t.middleware(({ ctx, next }) => { if (!ctx.session || !ctx.session.user) { throw new TRPCError({ code: "UNAUTHORIZED" }); } return next({ ctx: { session: { ...ctx.session, user: ctx.session.user }, }, }); }); export const protectedProcedure = t.procedure.use(enforceUserIsAuthed); ``` -------------------------------- ### Database Management Scripts Source: https://context7.com/nicoalbanese/kirimase/llms.txt Configuration and CLI commands for managing Drizzle database migrations and inspection. ```json { "scripts": { "db:generate": "drizzle-kit generate:pg", "db:migrate": "tsx lib/db/migrate.ts", "db:push": "drizzle-kit push:pg", "db:studio": "drizzle-kit studio" } } ``` ```bash # Generate migration files pnpm run db:generate # Apply migrations pnpm run db:migrate # Push schema changes directly (development) pnpm run db:push # Open Drizzle Studio for database inspection pnpm run db:studio ``` -------------------------------- ### Generate Resources with Kirimase Source: https://github.com/nicoalbanese/kirimase/blob/master/README.md Scaffold models, views, and controllers for your Next.js application using the 'kirimase generate' command, similar to 'rails scaffold'. ```bash kirimase generate ``` -------------------------------- ### Generate API Routes for Computers Source: https://context7.com/nicoalbanese/kirimase/llms.txt Creates Next.js API routes for CRUD operations on computers, including request validation using Zod and path revalidation. ```typescript // Generated: app/api/computers/route.ts import { NextResponse } from "next/server"; import { revalidatePath } from "next/cache"; import { z } from "zod"; import { createComputer, deleteComputer, updateComputer, } from "@/lib/api/computers/mutations"; import { getComputers } from "@/lib/api/computers/queries"; import { computerIdSchema, insertComputerParams, updateComputerParams, } from "@/lib/db/schema/computers"; export async function GET() { try { const { computers } = await getComputers(); return NextResponse.json({ computers }, { status: 200 }); } catch (err) { return NextResponse.json({ error: err }, { status: 500 }); } } export async function POST(req: Request) { try { const validatedData = insertComputerParams.parse(await req.json()); const { computer } = await createComputer(validatedData); revalidatePath("/computers"); return NextResponse.json(computer, { status: 201 }); } catch (err) { if (err instanceof z.ZodError) { return NextResponse.json({ error: err.issues }, { status: 400 }); } return NextResponse.json({ error: err }, { status: 500 }); } } export async function PUT(req: Request) { try { const { searchParams } = new URL(req.url); const id = searchParams.get("id"); const validatedData = updateComputerParams.parse(await req.json()); const validatedParams = computerIdSchema.parse({ id }); const { computer } = await updateComputer(validatedParams.id, validatedData); return NextResponse.json(computer, { status: 200 }); } catch (err) { if (err instanceof z.ZodError) { return NextResponse.json({ error: err.issues }, { status: 400 }); } return NextResponse.json({ error: err }, { status: 500 }); } } export async function DELETE(req: Request) { try { const { searchParams } = new URL(req.url); const id = searchParams.get("id"); const validatedParams = computerIdSchema.parse({ id }); const { computer } = await deleteComputer(validatedParams.id); return NextResponse.json(computer, { status: 200 }); } catch (err) { if (err instanceof z.ZodError) { return NextResponse.json({ error: err.issues }, { status: 400 }); } return NextResponse.json({ error: err }, { status: 500 }); } } ``` -------------------------------- ### Configure Resend Email Service Source: https://context7.com/nicoalbanese/kirimase/llms.txt Sets up the Resend client and provides a reusable function for sending emails. ```typescript // Generated: lib/email/index.ts import { Resend } from "resend"; export const resend = new Resend(process.env.RESEND_API_KEY); interface SendEmailProps { to: string; subject: string; react: React.ReactElement; } export const sendEmail = async ({ to, subject, react }: SendEmailProps) => { try { const { data, error } = await resend.emails.send({ from: "onboarding@resend.dev", to, subject, react, }); if (error) { console.error("Error sending email:", error); throw error; } return data; } catch (error) { console.error("Error sending email:", error); throw error; } }; ``` -------------------------------- ### Configure Clerk Authentication Middleware Source: https://context7.com/nicoalbanese/kirimase/llms.txt Sets up the Clerk authentication middleware to protect routes and define public access. ```typescript // Generated: middleware.ts import { authMiddleware } from "@clerk/nextjs"; export default authMiddleware({ publicRoutes: ["/api/webhooks(.*)"], }); export const config = { matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"], }; ``` -------------------------------- ### Prisma Schema for MySQL (PlanetScale) Source: https://context7.com/nicoalbanese/kirimase/llms.txt Defines the database schema using Prisma for a MySQL database, including client and Zod schema generation. Requires DATABASE_URL environment variable. ```prisma // Generated: prisma/schema.prisma generator client { provider = "prisma-client-js" } generator zod { provider = "zod-prisma" output = "../src/lib/db/schema" relationModel = true modelCase = "camelCase" modelSuffix = "Schema" } datasource db { provider = "mysql" url = env("DATABASE_URL") relationMode = "prisma" } model Computer { id String @id @default(cuid()) brand String cores Int createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } ``` -------------------------------- ### Generate Next.js Server Actions Source: https://context7.com/nicoalbanese/kirimase/llms.txt This snippet demonstrates the structure of generated server actions for creating, updating, and deleting records, including schema validation and error handling. ```typescript // Generated: lib/actions/computers.ts "use server"; import { revalidatePath } from "next/cache"; import { createComputer, deleteComputer, updateComputer, } from "@/lib/api/computers/mutations"; import { ComputerId, NewComputerParams, UpdateComputerParams, computerIdSchema, insertComputerParams, updateComputerParams, } from "@/lib/db/schema/computers"; const handleErrors = (e: unknown) => { const errMsg = "Error, please try again."; if (e instanceof Error) return e.message.length > 0 ? e.message : errMsg; if (e && typeof e === "object" && "error" in e) { const errAsStr = e.error as string; return errAsStr.length > 0 ? errAsStr : errMsg; } return errMsg; }; const revalidateComputers = () => revalidatePath("/computers"); export const createComputerAction = async (input: NewComputerParams) => { try { const payload = insertComputerParams.parse(input); await createComputer(payload); revalidateComputers(); } catch (e) { return handleErrors(e); } }; export const updateComputerAction = async (input: UpdateComputerParams) => { try { const payload = updateComputerParams.parse(input); await updateComputer(payload.id, payload); revalidateComputers(); } catch (e) { return handleErrors(e); } }; export const deleteComputerAction = async (input: ComputerId) => { try { const payload = computerIdSchema.parse({ id: input }); await deleteComputer(payload.id); revalidateComputers(); } catch (e) { return handleErrors(e); } }; ``` -------------------------------- ### Generate Database Mutations Source: https://context7.com/nicoalbanese/kirimase/llms.txt Handles creating, updating, and deleting computer records with input validation. Includes error handling and returning affected rows. ```typescript // Generated: lib/api/computers/mutations.ts import { db } from "@/lib/db/index"; import { eq } from "drizzle-orm"; import { ComputerId, NewComputerParams, UpdateComputerParams, updateComputerSchema, insertComputerSchema, computers, computerIdSchema, } from "@/lib/db/schema/computers"; export const createComputer = async (computer: NewComputerParams) => { const newComputer = insertComputerSchema.parse(computer); try { const [c] = await db.insert(computers).values(newComputer).returning(); return { computer: c }; } catch (err) { const message = (err as Error).message ?? "Error, please try again"; console.error(message); throw { error: message }; } }; export const updateComputer = async ( id: ComputerId, computer: UpdateComputerParams ) => { const { id: computerId } = computerIdSchema.parse({ id }); const newComputer = updateComputerSchema.parse({ ...computer, updatedAt: new Date(), }); try { const [c] = await db .update(computers) .set(newComputer) .where(eq(computers.id, computerId)) .returning(); return { computer: c }; } catch (err) { const message = (err as Error).message ?? "Error, please try again"; console.error(message); throw { error: message }; } }; export const deleteComputer = async (id: ComputerId) => { const { id: computerId } = computerIdSchema.parse({ id }); try { const [c] = await db .delete(computers) .where(eq(computers.id, computerId)) .returning(); return { computer: c }; } catch (err) { const message = (err as Error).message ?? "Error, please try again"; console.error(message); throw { error: message }; } }; ``` -------------------------------- ### Computer Management API Source: https://context7.com/nicoalbanese/kirimase/llms.txt Provides RESTful endpoints for managing computer resources. These endpoints handle request validation and interact with the underlying database mutations and queries. ```APIDOC ## GET /api/computers ### Description Retrieves a list of all computers. ### Method GET ### Endpoint /api/computers ### Response #### Success Response (200) - **computers** (array) - A list of computer objects. #### Response Example ```json { "computers": [ { "id": "some-uuid", "name": "Computer Name", "createdAt": "2023-10-27T10:00:00.000Z", "updatedAt": "2023-10-27T10:00:00.000Z" } ] } ``` ``` ```APIDOC ## POST /api/computers ### Description Creates a new computer. ### Method POST ### Endpoint /api/computers ### Request Body - **name** (string) - Required - The name of the computer. ### Request Example ```json { "name": "New Computer" } ``` ### Response #### Success Response (201) - **computer** (object) - The newly created computer object. #### Response Example ```json { "id": "new-uuid", "name": "New Computer", "createdAt": "2023-10-27T10:05:00.000Z", "updatedAt": "2023-10-27T10:05:00.000Z" } ``` ``` ```APIDOC ## PUT /api/computers ### Description Updates an existing computer. ### Method PUT ### Endpoint /api/computers?id={computerId} ### Query Parameters - **id** (string) - Required - The ID of the computer to update. ### Request Body - **name** (string) - Optional - The new name for the computer. ### Request Example ```json { "name": "Updated Computer Name" } ``` ### Response #### Success Response (200) - **computer** (object) - The updated computer object. #### Response Example ```json { "id": "some-uuid", "name": "Updated Computer Name", "createdAt": "2023-10-27T10:00:00.000Z", "updatedAt": "2023-10-27T10:10:00.000Z" } ``` ``` ```APIDOC ## DELETE /api/computers ### Description Deletes a computer. ### Method DELETE ### Endpoint /api/computers?id={computerId} ### Query Parameters - **id** (string) - Required - The ID of the computer to delete. ### Response #### Success Response (200) - **computer** (object) - The deleted computer object. #### Response Example ```json { "id": "some-uuid", "name": "Computer to Delete", "createdAt": "2023-10-27T10:00:00.000Z", "updatedAt": "2023-10-27T10:15:00.000Z" } ``` ``` -------------------------------- ### Implement Clerk Authentication Utilities Source: https://context7.com/nicoalbanese/kirimase/llms.txt Provides helper functions to retrieve user session data and enforce authentication checks. ```typescript // Generated: lib/auth/utils.ts (Clerk version) import { auth } from "@clerk/nextjs"; import { redirect } from "next/navigation"; export type AuthSession = { session: { user: { id: string; name?: string; email?: string; }; } | null; }; export const getUserAuth = async (): Promise => { const { userId, sessionClaims } = auth(); if (userId) { return { session: { user: { id: userId, name: sessionClaims?.name as string, email: sessionClaims?.email as string, }, }, }; } else { return { session: null }; } }; export const checkAuth = async () => { const { userId } = auth(); if (!userId) redirect("/sign-in"); }; ``` -------------------------------- ### Toggle Analytics Source: https://context7.com/nicoalbanese/kirimase/llms.txt Toggles the collection of anonymous analytics data for Kirimase on or off. ```bash kirimase analytics -t ``` -------------------------------- ### Create Stripe Checkout Session Source: https://context7.com/nicoalbanese/kirimase/llms.txt Generates a subscription checkout URL for an authenticated user. ```typescript // Generated: lib/stripe/subscription.ts import { db } from "@/lib/db/index"; import { getUserAuth } from "@/lib/auth/utils"; import { stripe } from "."; export async function createCheckoutLink(priceId: string) { const { session } = await getUserAuth(); if (!session) throw new Error("Unauthorized"); const user = await db.query.users.findFirst({ where: (users, { eq }) => eq(users.id, session.user.id), }); if (!user) throw new Error("User not found"); const stripeSession = await stripe.checkout.sessions.create({ mode: "subscription", payment_method_types: ["card"], line_items: [{ price: priceId, quantity: 1 }], success_url: `${process.env.NEXTAUTH_URL}/account/billing?success=true`, cancel_url: `${process.env.NEXTAUTH_URL}/account/billing?success=false`, customer_email: user.email, metadata: { userId: user.id }, }); return stripeSession.url; } ``` -------------------------------- ### Generate Database Queries Source: https://context7.com/nicoalbanese/kirimase/llms.txt Provides type-safe functions for querying computer data from the database. Requires Drizzle ORM and schema definitions. ```typescript // Generated: lib/api/computers/queries.ts import { db } from "@/lib/db/index"; import { eq } from "drizzle-orm"; import { type ComputerId, computerIdSchema, computers, } from "@/lib/db/schema/computers"; export const getComputers = async () => { const rows = await db.select().from(computers); const c = rows; return { computers: c }; }; export const getComputerById = async (id: ComputerId) => { const { id: computerId } = computerIdSchema.parse({ id }); const [row] = await db .select() .from(computers) .where(eq(computers.id, computerId)); if (row === undefined) return {}; const c = row; return { computer: c }; }; ``` -------------------------------- ### Generate Server-Side CRUD Page Source: https://context7.com/nicoalbanese/kirimase/llms.txt A server-side page component that fetches data using tRPC and renders a list and modal. ```typescript // Generated: app/(app)/computers/page.tsx import ComputerList from "@/components/computers/ComputerList"; import NewComputerModal from "@/components/computers/ComputerModal"; import { api } from "@/lib/trpc/api"; import { checkAuth } from "@/lib/auth/utils"; export default async function Computers() { await checkAuth(); const { computers } = await api.computers.getComputers.query(); return (

Computers

); } ``` -------------------------------- ### Database Access Functions Source: https://context7.com/nicoalbanese/kirimase/llms.txt These functions provide type-safe access to the database for computer-related operations. ```APIDOC ## getComputers() ### Description Retrieves all computers from the database. ### Returns - **computers** (array) - An array of computer objects. ### Example ```typescript const { computers } = await getComputers(); ``` ``` ```APIDOC ## getComputerById(id: ComputerId) ### Description Retrieves a single computer by its ID. ### Parameters - **id** (ComputerId) - Required - The ID of the computer to retrieve. ### Returns - **computer** (object) - The computer object if found, otherwise an empty object. ### Example ```typescript const { computer } = await getComputerById('some-uuid'); ``` ``` ```APIDOC ## createComputer(computer: NewComputerParams) ### Description Creates a new computer in the database. ### Parameters - **computer** (NewComputerParams) - Required - An object containing the new computer's data. ### Returns - **computer** (object) - The newly created computer object. ### Throws - **error** (string) - An error message if creation fails. ### Example ```typescript const { computer } = await createComputer({ name: 'New PC' }); ``` ``` ```APIDOC ## updateComputer(id: ComputerId, computer: UpdateComputerParams) ### Description Updates an existing computer in the database. ### Parameters - **id** (ComputerId) - Required - The ID of the computer to update. - **computer** (UpdateComputerParams) - Required - An object containing the updated computer data. ### Returns - **computer** (object) - The updated computer object. ### Throws - **error** (string) - An error message if update fails. ### Example ```typescript const { computer } = await updateComputer('some-uuid', { name: 'Updated PC Name' }); ``` ``` ```APIDOC ## deleteComputer(id: ComputerId) ### Description Deletes a computer from the database. ### Parameters - **id** (ComputerId) - Required - The ID of the computer to delete. ### Returns - **computer** (object) - The deleted computer object. ### Throws - **error** (string) - An error message if deletion fails. ### Example ```typescript const { computer } = await deleteComputer('some-uuid'); ``` ``` -------------------------------- ### Generate CRUD tRPC Router Source: https://context7.com/nicoalbanese/kirimase/llms.txt Defines a router with standard CRUD procedures for a specific resource. ```typescript // Generated: lib/server/routers/computers.ts import { getComputerById, getComputers } from "@/lib/api/computers/queries"; import { createComputer, deleteComputer, updateComputer, } from "@/lib/api/computers/mutations"; import { computerIdSchema, insertComputerParams, updateComputerParams, } from "@/lib/db/schema/computers"; import { publicProcedure, router } from "../trpc"; export const computersRouter = router({ getComputers: publicProcedure.query(async () => { return getComputers(); }), getComputerById: publicProcedure .input(computerIdSchema) .query(async ({ input }) => { return getComputerById(input.id); }), createComputer: publicProcedure .input(insertComputerParams) .mutation(async ({ input }) => { return createComputer(input); }), updateComputer: publicProcedure .input(updateComputerParams) .mutation(async ({ input }) => { return updateComputer(input.id, input); }), deleteComputer: publicProcedure .input(computerIdSchema) .mutation(async ({ input }) => { return deleteComputer(input.id); }), }); ``` -------------------------------- ### Define tRPC Application Router Source: https://context7.com/nicoalbanese/kirimase/llms.txt Aggregates sub-routers into the main application router. ```typescript // Generated: lib/server/routers/_app.ts import { router } from "../trpc"; import { computersRouter } from "./computers"; export const appRouter = router({ computers: computersRouter, }); export type AppRouter = typeof appRouter; ``` -------------------------------- ### Generate Client-Side CRUD Form Source: https://context7.com/nicoalbanese/kirimase/llms.txt A client-side form component using react-hook-form and Zod for validation, handling create, update, and delete mutations via tRPC. ```typescript // Generated: components/computers/ComputerForm.tsx "use client"; import { Computer, NewComputerParams, insertComputerParams } from "@/lib/db/schema/computers"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { Input } from "@/components/ui/input"; import { trpc } from "@/lib/trpc/client"; import { Button } from "@/components/ui/button"; import { z } from "zod"; import { useRouter } from "next/navigation"; import { toast } from "sonner"; const ComputerForm = ({ computer, closeModal, }: { computer?: Computer; closeModal?: () => void; }) => { const editing = !!computer?.id; const router = useRouter(); const utils = trpc.useUtils(); const form = useForm>({ resolver: zodResolver(insertComputerParams), defaultValues: computer ?? { brand: "", cores: 0, }, }); const onSuccess = async (action: "create" | "update" | "delete") => { await utils.computers.getComputers.invalidate(); router.refresh(); if (closeModal) closeModal(); toast.success(`Computer ${action}d!`); }; const { mutate: createComputer, isLoading: isCreating } = trpc.computers.createComputer.useMutation({ onSuccess: () => onSuccess("create"), }); const { mutate: updateComputer, isLoading: isUpdating } = trpc.computers.updateComputer.useMutation({ onSuccess: () => onSuccess("update"), }); const { mutate: deleteComputer, isLoading: isDeleting } = trpc.computers.deleteComputer.useMutation({ onSuccess: () => onSuccess("delete"), }); const handleSubmit = (values: NewComputerParams) => { if (editing) { updateComputer({ ...values, id: computer.id }); } else { createComputer(values); } }; return (
( Brand )} /> ( Cores )} /> {editing && ( )} ); }; export default ComputerForm; ``` -------------------------------- ### Create Server-Side tRPC Caller Source: https://context7.com/nicoalbanese/kirimase/llms.txt Enables server-side calls to the tRPC API, typically used in Server Components. ```typescript // Generated: lib/trpc/api.ts (server-side) import "server-only"; import { appRouter } from "@/lib/server/routers/_app"; import { createTRPCContext } from "@/lib/server/trpc"; import { headers } from "next/headers"; export const api = appRouter.createCaller( await createTRPCContext({ headers: headers() }) ); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.