Introduction#
GitHub this note show
- setup nextjs and prisma
- server function
Setup Project#
Let setup a new nextjs project
npx create-next-app@latest
Install dependencies
npm install prisma --save-dev
And install prisma client
npm install @prisma/client
Init the prsima schema, and this will create a prisma directory and we can configure the schema
npx prisma init --datasource-provider sqlite
Finally, run the following command to create db file
npx prisma generate
Create prisma.ts in the lib directory as the following
import { PrismaClient } from '@prisma/client'const globalForPrisma = global as unknown as {prisma: PrismaClient | undefined}export const prisma =globalForPrisma.prisma ??new PrismaClient({log: []})if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma
Prisma Schema#
generator client {provider = "prisma-client-js"}datasource db {provider = "sqlite"url = env("DATABASE_URL")}model Post {id Int @id @default(autoincrement())title Stringcontent String}
Run this command to create .db file in prsima
npx prisma generate
Post Page#
To create a post we need
async function createPost(data: any) {'use server'let { title, content } = Object.fromEntries(data)let post = await prisma.post.create({data: {title,content}})console.log(post)revalidatePath('/')}
Use a form to create and save the post
<form action={createPost} className="w-full mt-4 space-y-4"><div><inputclassName="w-full border p-2"placeholder="Title"type="text"name="title"required></input></div><div><textareaclassName="w-full border p-2"placeholder="write something intesting ..."name="content"required></textarea></div><div className="text-right"><button className="font-medium bg-sky-500 text-white px-3 py-1">Create Post</button></div></form>
Then we can query a post by id and display it in /post/[id]/page.tsx
import { prisma } from '@/lib/prisma'export default async function Post({ params }: { params: any }) {let post: any = await prisma.post.findUnique({ where: { id: +params.id } })return (post && (<div className="max-w-4xl mx-auto"><p className="text-2xl font-bold text-gray-700">{post.title}</p><div className="mt-6"><pre className="font-sans whitespace-pre-line">{post.content}</pre></div></div>))}
Query all post and display them in the home page
let posts = await prisma.post.findMany({ orderBy: { id: 'desc' } })<div><p>All post</p><div>{posts.map((post: any) => (<div key={post.id}><Linkhref={`/post/${post.id}`}className="underline underline-offset-2 decoration-gray-300">{post.title}</Link></div>))}</div></div>