iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📍

Writing Next.js + Prisma with the Concept of Colocation

に公開

With the App Router in Next.js, it has become practical to execute SQL queries directly from React components using the Prisma client.

I realized that you can execute Prisma queries using the same concept as GraphQL Fragments, which is a form of colocation, so I would like to introduce it.

Sample Code

Sample code is available in the following repository.
https://github.com/odan-sandbox/nextjs-prisma-colocation-sandbox

Model

This is the model used for this explanation.
We will consider the implementation of a component that displays this Post model.

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}

model Post {
  id        Int     @id @default(autoincrement())
  title     String
  content   String?
  published Boolean @default(false)
  author    User    @relation(fields: [authorId], references: [id])
  authorId  Int
}

Naive Implementation

If we implement a component that displays all Posts along with the name of each Post's author, it would look something like this:

PostList.tsx
import { Post, User } from "@prisma/client";

type Props = {
  posts: (Post & { author: User })[];
};

export const PostList = ({ posts }: Props) => {
  return (
    <div>
      <h1>Post List</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>
            {post.author.name}: {post.title}
          </li>
        ))}
      </ul>
    </div>
  );
};

It is used from the parent component as follows:

export default async function Home() {
  const posts = await prisma.post.findMany({ include: { author: true } });
  return (
    <div>
      <PostList posts={posts} />
    </div>
  );
}

In this implementation, the type definition for posts is in the child component, while the query to fetch the data is in the parent component, meaning the responsibilities are fragmented.

Implementation Inspired by Fragments

If we can infer the return value from the { include: { author: true } } passed as an argument to prisma.post.findMany, it becomes possible to implement both the query specification and type definition within the child component.

Actually, Prisma provides Utility Types for performing this kind of type inference.
https://www.prisma.io/docs/concepts/components/prisma-client/advanced-type-safety/operating-against-partial-structures-of-model-types#problem-using-variations-of-the-generated-model-type

Using these, the child component from earlier can be implemented as follows:

PostList2.tsx
export const getPostsQuery = Prisma.validator<Prisma.PostDefaultArgs>()({
  include: { author: true },
});

type Post = Prisma.PostGetPayload<typeof getPostsQuery>;

type Props = {
  posts: Post[];
};

export const PostList2 = ({ posts }: Props) => {
  return (
    <div>
      <h1>Post List</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>
            {post.author.name}: {post.title}
          </li>
        ))}
      </ul>
    </div>
  );
};

In the parent component, you import getPostsQuery and issue the query.

export default async function Home() {
  const posts2 = await prisma.post.findMany(getPostsQuery);
  return (
    <div>
      <PostList2 posts={posts2} />
    </div>
  );
}

Summary

I have introduced a way to centralize queries and type definitions in components using Prisma, drawing inspiration from GraphQL Fragments.

Discussion