feat(01-01): wire Clerk proxy.ts, Prisma 7 schema + singleton, tRPC stack, R2 client, ActivePetContext
- Create proxy.ts at repo root with clerkMiddleware + createRouteMatcher (public allowlist: sign-up, log-in, forgot-password, reset-password, verify-email) - Create prisma/schema.prisma: Owner, Species, Breed, Pet models with ownership index and FK constraints - Create prisma.config.ts with Prisma 7 defineConfig (datasource url via env) - Create src/lib/prisma.ts: Prisma 7 singleton using @prisma/adapter-pg for local dev, withAccelerate() for Prisma Accelerate on Vercel - Create src/lib/r2.ts (server-only): S3Client + getPresignedUploadUrl with contentType enforcement and 300s expiry - Create src/lib/auth.ts: getOwnerId() Clerk auth wrapper - Create src/trpc/init.ts: createTRPCContext, router, publicProcedure, protectedProcedure (throws UNAUTHORIZED) - Create src/trpc/routers/pets.ts: pets.create (upserts Owner, creates Pet with ownerId=ctx.userId), pets.list (scoped), pets.byId (ownership-asserted) - Create src/trpc/routers/_app.ts: appRouter + AppRouter type export - Create src/trpc/query-client.ts, server.ts (RSC caller), client.tsx (TRPCReactProvider + useTRPC) - Create src/app/api/trpc/[trpc]/route.ts: tRPC fetch handler (GET + POST) - Create src/context/ActivePetContext.tsx + src/hooks/useActivePet.ts: localStorage-backed active pet context - Create prisma/seed.ts: seeds Dog/Cat/Bird species idempotently via upsert - Update src/app/layout.tsx: wrap children in ClerkProvider (orange primary), TRPCReactProvider, ActivePetProvider, Toaster - Install @prisma/adapter-pg + pg for Prisma 7 local dev (Rule 2: required for Prisma 7 engine compatibility) - [Rule 1 - Bug] Prisma 7 no longer supports url/directUrl in schema.prisma; moved to prisma.config.ts with defineConfig
This commit is contained in:
1 parent
dbc074e9ee
commit
e0214ea0f8
22 files changed
+1402
-3
No files matched your search
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* App shell layout — applied to all routes under /(app)/
|
||||
* Clerk's proxy.ts enforces authentication before this layout renders.
|
||||
*
|
||||
* This is a minimal skeleton layout for Phase 1.
|
||||
* Full navigation (sidebar, pet switcher) is implemented in Plan 02.
|
||||
*/
|
||||
export default function AppLayout({ children }: { children: React.ReactNode }) {
|
||||
return <div className="min-h-screen bg-background">{children}</div>;
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTRPC } from "@/trpc/client";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { toast } from "sonner";
|
||||
|
||||
/**
|
||||
* Pet onboarding page — /onboarding/pet
|
||||
* Minimal form to create the first pet profile (walking skeleton).
|
||||
*
|
||||
* Full form (breed selector, avatar upload, bio, adoption story) is
|
||||
* implemented in Plan 02/03. This page proves the end-to-end tRPC flow.
|
||||
*/
|
||||
export default function OnboardingPetPage() {
|
||||
const router = useRouter();
|
||||
const trpc = useTRPC();
|
||||
const [name, setName] = useState("");
|
||||
|
||||
// pets.create mutation via tRPC
|
||||
const createPet = useMutation(
|
||||
trpc.pets.create.mutationOptions({
|
||||
onSuccess: (pet) => {
|
||||
toast.success(`Pet profile created for ${pet.name}!`);
|
||||
router.push("/pets");
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err.message || "Failed to create pet profile.");
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!name.trim()) return;
|
||||
// Using a placeholder speciesId — real species selector in Plan 02
|
||||
createPet.mutate({ name: name.trim(), speciesId: "placeholder" });
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="container max-w-md mx-auto px-6 py-12">
|
||||
<h1 className="text-xl font-semibold mb-2">Add your first pet</h1>
|
||||
<p className="text-sm text-muted-foreground mb-8">
|
||||
Your pet will be their own star on OnlyPets.
|
||||
</p>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="pet-name">Pet name</Label>
|
||||
<Input
|
||||
id="pet-name"
|
||||
placeholder="e.g. Buddy, Luna, Max"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
maxLength={30}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={createPet.isPending || !name.trim()}
|
||||
>
|
||||
{createPet.isPending ? "Adding pet…" : "Add Pet"}
|
||||
</Button>
|
||||
</form>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { createTRPCCaller } from "@/trpc/server";
|
||||
|
||||
/**
|
||||
* My Pets page — /pets
|
||||
* Lists all pets belonging to the authenticated owner.
|
||||
*
|
||||
* This is a skeleton page for Phase 1 walking skeleton.
|
||||
* Full UI (grid, pet cards, add pet CTA) is implemented in Plan 02/03.
|
||||
*/
|
||||
export default async function PetsPage() {
|
||||
const trpc = await createTRPCCaller();
|
||||
const pets = await trpc.pets.list();
|
||||
|
||||
return (
|
||||
<main className="container max-w-2xl mx-auto px-6 py-8">
|
||||
<h1 className="text-xl font-semibold mb-6">My Pets</h1>
|
||||
{pets.length === 0 ? (
|
||||
<p className="text-muted-foreground">
|
||||
You haven't added any pets yet.{" "}
|
||||
<a href="/onboarding/pet" className="text-primary hover:underline">
|
||||
Add your first pet
|
||||
</a>
|
||||
</p>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{pets.map((pet) => (
|
||||
<li key={pet.id} className="p-4 border rounded-lg">
|
||||
<span className="font-semibold">{pet.name}</span>
|
||||
<span className="ml-2 text-xs text-muted-foreground">
|
||||
{pet.species.name}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
|
||||
import { appRouter } from "@/trpc/routers/_app";
|
||||
import { createTRPCContext } from "@/trpc/init";
|
||||
|
||||
/**
|
||||
* tRPC fetch handler for Next.js App Router.
|
||||
* Handles all tRPC requests via the /api/trpc endpoint.
|
||||
*/
|
||||
const handler = (req: Request) =>
|
||||
fetchRequestHandler({
|
||||
endpoint: "/api/trpc",
|
||||
req,
|
||||
router: appRouter,
|
||||
createContext: createTRPCContext,
|
||||
});
|
||||
|
||||
export { handler as GET, handler as POST };
|
||||
+24
-3
@@ -1,5 +1,9 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Inter } from "next/font/google";
|
||||
import { ClerkProvider } from "@clerk/nextjs";
|
||||
import { TRPCReactProvider } from "@/trpc/client";
|
||||
import { ActivePetProvider } from "@/context/ActivePetContext";
|
||||
import { Toaster } from "@/components/ui/sonner";
|
||||
import "./globals.css";
|
||||
|
||||
const inter = Inter({
|
||||
@@ -18,8 +22,25 @@ export default function RootLayout({
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang="en" className={`${inter.variable} h-full antialiased font-sans`}>
|
||||
<body className="min-h-full flex flex-col">{children}</body>
|
||||
</html>
|
||||
<ClerkProvider
|
||||
appearance={{
|
||||
variables: {
|
||||
colorPrimary: "#F97316",
|
||||
colorBackground: "#FAFAFA",
|
||||
colorText: "#09090B",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<html lang="en" className={`${inter.variable} h-full antialiased font-sans`}>
|
||||
<body className="min-h-full flex flex-col">
|
||||
<TRPCReactProvider>
|
||||
<ActivePetProvider>
|
||||
{children}
|
||||
<Toaster />
|
||||
</ActivePetProvider>
|
||||
</TRPCReactProvider>
|
||||
</body>
|
||||
</html>
|
||||
</ClerkProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
"use client";
|
||||
|
||||
import { createContext, useContext, useState, useEffect } from "react";
|
||||
|
||||
/**
|
||||
* Active Pet Context — tracks the currently active pet for the logged-in owner.
|
||||
*
|
||||
* Architecture:
|
||||
* - Active pet id is stored in React Context (client-side only) + localStorage for persistence.
|
||||
* - RSC fallback: if no localStorage value, the first pet in the list is shown (set by the
|
||||
* app shell after fetching the owner's pets).
|
||||
* - Switching active pet does NOT require a page reload.
|
||||
*
|
||||
* Note: RSC cannot read localStorage. Server-side rendering uses the first pet as fallback.
|
||||
* The hydration mismatch is expected on first load; localStorage takes over on the client.
|
||||
*/
|
||||
|
||||
type ActivePetContextType = {
|
||||
activePetId: string | null;
|
||||
setActivePet: (id: string) => void;
|
||||
};
|
||||
|
||||
const ActivePetContext = createContext<ActivePetContextType | null>(null);
|
||||
|
||||
const STORAGE_KEY = "active_pet_id";
|
||||
|
||||
export function ActivePetProvider({ children }: { children: React.ReactNode }) {
|
||||
const [activePetId, setActivePetId] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
// Initialize from localStorage on client mount (avoids SSR mismatch)
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (stored) setActivePetId(stored);
|
||||
}, []);
|
||||
|
||||
const setActivePet = (id: string) => {
|
||||
setActivePetId(id);
|
||||
localStorage.setItem(STORAGE_KEY, id);
|
||||
};
|
||||
|
||||
return (
|
||||
<ActivePetContext.Provider value={{ activePetId, setActivePet }}>
|
||||
{children}
|
||||
</ActivePetContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useActivePet(): ActivePetContextType {
|
||||
const ctx = useContext(ActivePetContext);
|
||||
if (!ctx) {
|
||||
throw new Error("useActivePet must be used inside <ActivePetProvider>");
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
"use client";
|
||||
|
||||
export { useActivePet } from "@/context/ActivePetContext";
|
||||
@@ -0,0 +1,19 @@
|
||||
import "server-only";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
|
||||
/**
|
||||
* Server-side Clerk auth helpers.
|
||||
* These wrappers ensure consistent access to the current owner's identity.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns the Clerk userId for the currently signed-in owner, or null if
|
||||
* the request is unauthenticated. Use in RSC and server-side code.
|
||||
*
|
||||
* For tRPC procedures, prefer reading ctx.userId directly from the context
|
||||
* (set by createTRPCContext) rather than calling this function.
|
||||
*/
|
||||
export async function getOwnerId(): Promise<string | null> {
|
||||
const { userId } = await auth();
|
||||
return userId;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import "server-only";
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import { withAccelerate } from "@prisma/extension-accelerate";
|
||||
import { PrismaPg } from "@prisma/adapter-pg";
|
||||
import { Pool } from "pg";
|
||||
|
||||
/**
|
||||
* Prisma 7 singleton for Next.js / serverless environments.
|
||||
*
|
||||
* Prisma 7 requires either an `adapter` (for direct DB connections)
|
||||
* or an `accelerateUrl` (for Prisma Accelerate on Vercel).
|
||||
*
|
||||
* Local dev: uses @prisma/adapter-pg with a pg Pool (direct Supabase connection).
|
||||
* Vercel/Accelerate: set PRISMA_ACCELERATE_URL and this will use withAccelerate().
|
||||
*/
|
||||
|
||||
const globalForPrisma = globalThis as unknown as {
|
||||
prisma: PrismaClient | undefined;
|
||||
};
|
||||
|
||||
function createPrismaClient(): PrismaClient {
|
||||
const accelerateUrl = process.env.PRISMA_ACCELERATE_URL;
|
||||
const databaseUrl = process.env.DATABASE_URL;
|
||||
|
||||
if (accelerateUrl) {
|
||||
// Prisma Accelerate path (Vercel production / staging)
|
||||
const client = new PrismaClient({ accelerateUrl });
|
||||
return client.$extends(withAccelerate()) as unknown as PrismaClient;
|
||||
}
|
||||
|
||||
if (!databaseUrl) {
|
||||
throw new Error(
|
||||
"DATABASE_URL environment variable is not set. " +
|
||||
"Please add it to .env.local with your Supabase connection string."
|
||||
);
|
||||
}
|
||||
|
||||
// Local dev / direct Supabase connection path
|
||||
const adapter = new PrismaPg(new Pool({ connectionString: databaseUrl }));
|
||||
return new PrismaClient({ adapter });
|
||||
}
|
||||
|
||||
export const prisma = globalForPrisma.prisma ?? createPrismaClient();
|
||||
|
||||
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
|
||||
@@ -0,0 +1,43 @@
|
||||
import "server-only";
|
||||
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
|
||||
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
|
||||
|
||||
/**
|
||||
* Cloudflare R2 client configured for presigned PUT uploads.
|
||||
* This module is server-only — R2 credentials never reach the client bundle.
|
||||
*
|
||||
* Media bytes NEVER go through the API server.
|
||||
* Flow: tRPC procedure generates presigned URL → client PUTs directly to R2.
|
||||
*/
|
||||
export const r2 = new S3Client({
|
||||
region: "auto", // required by SDK but not used by R2
|
||||
endpoint: `https://${process.env.CF_ACCOUNT_ID}.r2.cloudflarestorage.com`,
|
||||
credentials: {
|
||||
accessKeyId: process.env.R2_ACCESS_KEY_ID!,
|
||||
secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Generate a presigned PUT URL for direct client-side upload to R2.
|
||||
* The contentType MUST match what the browser sends in the PUT request
|
||||
* (mismatch causes R2 to return 403 SignatureDoesNotMatch).
|
||||
*
|
||||
* @param key - R2 object key (e.g. "avatars/owner_xxx_1234567890.jpg")
|
||||
* @param contentType - MIME type of the file being uploaded
|
||||
* @returns A presigned URL string valid for 5 minutes
|
||||
*/
|
||||
export async function getPresignedUploadUrl(
|
||||
key: string,
|
||||
contentType: "image/jpeg" | "image/png" | "image/webp"
|
||||
): Promise<string> {
|
||||
return getSignedUrl(
|
||||
r2,
|
||||
new PutObjectCommand({
|
||||
Bucket: process.env.R2_BUCKET_NAME!,
|
||||
Key: key,
|
||||
ContentType: contentType, // must match what browser sends in PUT
|
||||
}),
|
||||
{ expiresIn: 300 } // 5 minutes
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
"use client";
|
||||
|
||||
import { createTRPCClient, httpBatchLink } from "@trpc/client";
|
||||
import { createTRPCContext as createTRPCReactContext } from "@trpc/tanstack-react-query";
|
||||
import { useState } from "react";
|
||||
import { QueryClientProvider } from "@tanstack/react-query";
|
||||
import { makeQueryClient } from "@/trpc/query-client";
|
||||
import type { AppRouter } from "@/trpc/routers/_app";
|
||||
|
||||
/**
|
||||
* tRPC + TanStack Query React context.
|
||||
* Provides the useTRPC hook for client components.
|
||||
*/
|
||||
export const { TRPCProvider, useTRPC } = createTRPCReactContext<AppRouter>();
|
||||
|
||||
let clientQueryClientSingleton: ReturnType<typeof makeQueryClient> | undefined;
|
||||
|
||||
function getQueryClient() {
|
||||
if (typeof window === "undefined") {
|
||||
// Server: always create a new QueryClient
|
||||
return makeQueryClient();
|
||||
}
|
||||
// Browser: use singleton to avoid recreating on each render
|
||||
if (!clientQueryClientSingleton) {
|
||||
clientQueryClientSingleton = makeQueryClient();
|
||||
}
|
||||
return clientQueryClientSingleton;
|
||||
}
|
||||
|
||||
export function TRPCReactProvider({ children }: { children: React.ReactNode }) {
|
||||
const queryClient = getQueryClient();
|
||||
|
||||
const [trpcClient] = useState(() =>
|
||||
createTRPCClient<AppRouter>({
|
||||
links: [
|
||||
httpBatchLink({
|
||||
url: "/api/trpc",
|
||||
}),
|
||||
],
|
||||
})
|
||||
);
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<TRPCProvider trpcClient={trpcClient} queryClient={queryClient}>
|
||||
{children}
|
||||
</TRPCProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { initTRPC, TRPCError } from "@trpc/server";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
/**
|
||||
* tRPC context — created per request in the API route handler.
|
||||
* Reads the authenticated owner's Clerk userId and provides the Prisma client.
|
||||
*/
|
||||
export const createTRPCContext = async () => {
|
||||
const { userId } = await auth();
|
||||
return { userId, prisma };
|
||||
};
|
||||
|
||||
type Context = Awaited<ReturnType<typeof createTRPCContext>>;
|
||||
|
||||
const t = initTRPC.context<Context>().create();
|
||||
|
||||
export const router = t.router;
|
||||
export const publicProcedure = t.procedure;
|
||||
|
||||
/**
|
||||
* Protected procedure — throws UNAUTHORIZED if no userId in context.
|
||||
* All pet mutations and scoped queries must use this procedure.
|
||||
*/
|
||||
export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
|
||||
if (!ctx.userId) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
return next({
|
||||
ctx: {
|
||||
...ctx,
|
||||
userId: ctx.userId, // narrow to non-null string
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import {
|
||||
defaultShouldDehydrateQuery,
|
||||
QueryClient,
|
||||
} from "@tanstack/react-query";
|
||||
|
||||
/**
|
||||
* Factory function for creating a QueryClient with default settings.
|
||||
* Called once per request (server-side) or once on the client.
|
||||
*/
|
||||
export function makeQueryClient() {
|
||||
return new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
// With SSR we usually want to set staleTime > 0 to avoid refetching
|
||||
// immediately on the client after SSR hydration.
|
||||
staleTime: 30 * 1000, // 30 seconds
|
||||
},
|
||||
dehydrate: {
|
||||
// Include pending queries in dehydration for RSC streaming
|
||||
shouldDehydrateQuery: (query) =>
|
||||
defaultShouldDehydrateQuery(query) ||
|
||||
query.state.status === "pending",
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { router } from "@/trpc/init";
|
||||
import { petsRouter } from "@/trpc/routers/pets";
|
||||
|
||||
export const appRouter = router({
|
||||
pets: petsRouter,
|
||||
});
|
||||
|
||||
// Export the type for use in the client
|
||||
export type AppRouter = typeof appRouter;
|
||||
@@ -0,0 +1,103 @@
|
||||
import { z } from "zod";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { router, protectedProcedure } from "@/trpc/init";
|
||||
|
||||
/**
|
||||
* Ownership assertion helper — verifies that a pet belongs to the requesting
|
||||
* owner before any mutation or scoped query proceeds.
|
||||
*
|
||||
* Security (T-1-02): never trust client-supplied pet ids without DB verification.
|
||||
* Every pet mutation asserts pet.ownerId === ctx.userId (ASVS V4).
|
||||
*/
|
||||
async function assertPetOwnership(
|
||||
prisma: Parameters<Parameters<typeof protectedProcedure.mutation>[0]>[0]["ctx"]["prisma"],
|
||||
petId: string,
|
||||
userId: string
|
||||
) {
|
||||
const pet = await prisma.pet.findUnique({ where: { id: petId } });
|
||||
if (!pet || pet.ownerId !== userId) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "You do not have permission to access this pet.",
|
||||
});
|
||||
}
|
||||
return pet;
|
||||
}
|
||||
|
||||
export const petsRouter = router({
|
||||
/**
|
||||
* Create a new pet for the authenticated owner.
|
||||
* Upserts the Owner row first (ensures FK exists for new Clerk users).
|
||||
*
|
||||
* Security: ownerId is always set from ctx.userId (server-side) — never from client input.
|
||||
*/
|
||||
create: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
name: z.string().min(1).max(30),
|
||||
speciesId: z.string().min(1),
|
||||
breedId: z.string().optional(),
|
||||
bio: z.string().max(150).optional(),
|
||||
adoptionStory: z.string().max(500).optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
// Upsert Owner row from ctx.userId (ensures FK constraint is satisfied)
|
||||
await ctx.prisma.owner.upsert({
|
||||
where: { id: ctx.userId },
|
||||
update: {},
|
||||
create: { id: ctx.userId },
|
||||
});
|
||||
|
||||
return ctx.prisma.pet.create({
|
||||
data: {
|
||||
ownerId: ctx.userId,
|
||||
name: input.name,
|
||||
speciesId: input.speciesId,
|
||||
breedId: input.breedId ?? null,
|
||||
bio: input.bio ?? null,
|
||||
adoptionStory: input.adoptionStory ?? null,
|
||||
},
|
||||
});
|
||||
}),
|
||||
|
||||
/**
|
||||
* List all pets belonging to the authenticated owner.
|
||||
* Scoped by ownerId — never returns other owners' pets.
|
||||
*/
|
||||
list: protectedProcedure.query(async ({ ctx }) => {
|
||||
return ctx.prisma.pet.findMany({
|
||||
where: { ownerId: ctx.userId },
|
||||
include: {
|
||||
species: true,
|
||||
breed: true,
|
||||
},
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
}),
|
||||
|
||||
/**
|
||||
* Get a single pet by id.
|
||||
* Asserts ownership: returns FORBIDDEN if the pet doesn't belong to the requesting owner.
|
||||
*/
|
||||
byId: protectedProcedure
|
||||
.input(z.object({ petId: z.string().min(1) }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
const pet = await ctx.prisma.pet.findUnique({
|
||||
where: { id: input.petId },
|
||||
include: {
|
||||
species: true,
|
||||
breed: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!pet || pet.ownerId !== ctx.userId) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "You do not have permission to access this pet.",
|
||||
});
|
||||
}
|
||||
|
||||
return pet;
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import "server-only";
|
||||
import { appRouter } from "@/trpc/routers/_app";
|
||||
import { createTRPCContext } from "@/trpc/init";
|
||||
import { cache } from "react";
|
||||
|
||||
/**
|
||||
* Server-side tRPC caller for use in React Server Components (RSC).
|
||||
* Prefetch data in RSC layouts / page.tsx to hydrate the client.
|
||||
*
|
||||
* Usage in RSC:
|
||||
* const trpc = await createTRPCCaller();
|
||||
* const pets = await trpc.pets.list();
|
||||
*/
|
||||
export const createTRPCCaller = cache(async () => {
|
||||
const ctx = await createTRPCContext();
|
||||
return appRouter.createCaller(ctx);
|
||||
});
|
||||
Reference in new issue
Block a user