npx create-next-app@latest aws-rds-setup
npm install @prisma/client prisma
npx prisma init
DATABASE_URL="postgresql://USERNAME:PASSWORD@ENDPOINT:5432/postgres"
model Person {
id Int @id @default(autoincrement())
name String
age Int
email String @unique
address String
occupation String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
npx prisma generate
npx prisma db push
npx prisma studio
import { PrismaClient } from "@prisma/client";
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined;
};
export const prisma = globalForPrisma.prisma ?? new PrismaClient();
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
export async function GET() {
try {
const people = await prisma.person.findMany({
orderBy: {
createdAt: 'desc',
},
});
return NextResponse.json(people);
} catch (err) {
console.error('Failed to fetch people:', err);
return NextResponse.json(
{ error: 'Failed to fetch people' },
{ status: 500 }
);
}
}
import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
export async function POST(request: Request) {
try {
const body = await request.json();
const { name, age, email, address, occupation } = body;
const person = await prisma.person.create({
data: {
name,
age: parseInt(age),
email,
address,
occupation,
},
});
return NextResponse.json(person);
} catch (err) {
console.error('Failed to create person:', err);
return NextResponse.json(
{ error: 'Failed to create person' },
{ status: 500 }
);
}
}
'use client';
import { useState, useEffect } from 'react';
interface Person {
id: number;
name: string;
age: number;
email: string;
address: string;
occupation: string;
}
export default function Home() {
const [people, setPeople] = useState<Person[]>([]);
const [formData, setFormData] = useState({
name: '',
age: '',
email: '',
address: '',
occupation: '',
});
useEffect(() => {
fetchPeople();
}, []);
const fetchPeople = async () => {
try {
const response = await fetch('/api/people/get');
const data = await response.json();
setPeople(data);
} catch (error) {
console.error('Error fetching people:', error);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
const response = await fetch('/api/people/post', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
});
if (response.ok) {
setFormData({
name: '',
age: '',
email: '',
address: '',
occupation: '',
});
fetchPeople();
}
} catch (error) {
console.error('Error adding person:', error);
}
};
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setFormData({
...formData,
[e.target.name]: e.target.value,
});
};
return (
<main className="min-h-screen bg-white p-8">
...
</main>
);
}