article

Friday, February 9, 2024

NextJS 14 CRUD REST API using Prisma with MYSQL

NextJS 14 CRUD REST API using Prisma with MYSQL

Prisma is an open-source next-generation ORM. It consists of the following parts: Prisma Client: Auto-generated and type-safe query builder
https://www.prisma.io

Install prisma/client
npm install @prisma/client
https://www.prisma.io/docs/orm/prisma-client/setup-and-configuration/generating-prisma-client

Generate Prisma Client with the following command:
npx prisma generate

Install prisma
npm install prisma --save-dev
https://www.prisma.io/docs/getting-started/quickstart

set up Prisma with the init command of the Prisma CLI:
npx prisma init --datasource-provider sqlite
to npx prisma init --datasource-provider mysql

Model data in the Prisma schema
prisma/schema.prisma
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}

Run a migration to create your database tables with Prisma Migrate
npx prisma migrate dev --name init

.env
DATABASE_URL="mysql://root:root@localhost:8889/nextjsdb"

https://www.prisma.io/docs/orm/prisma-client/queries/crud

https://nextjs.org/docs/app/building-your-application/routing/route-handlers

Create Folder and Files
app\users\route.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//app\users\route.js
import { NextResponse } from "next/server";
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
 
export async function POST(request) {
    try {
        const data = await request.json();
        console.log(data);
        const { name, email } = data
 
        const newUser = await prisma.user.create({
            data: {
                name,
                email
            }
        });
        return NextResponse.json(newUser);
    } catch (error) {
        console.log("Error creating user:", error)
        return NextResponse.error("Internal Server Error", 500)
    }
}
 
export async function GET() {
    try {
        const users = await prisma.user.findMany();
        return NextResponse.json(users);
    } catch (error) {
        console.error("Error fetching users:", error);
        return NextResponse.error("Internal Server Error", 500);
    }
}
app\users\[id]\route.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//app\users\[id]\route.js
import { NextResponse } from "next/server";
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
 
export async function GET(request, { params }) {
    const id = parseInt(params.id);
    try {
        const users = await prisma.user.findUnique({
        where: {
            id: id,
        },
        })
        return NextResponse.json(users);
    } catch (error) {
        console.error("Error fetching users:", error);
        return NextResponse.error("Internal Server Error", 500);
    }
}
 
export async function PUT(request, { params }) {
    try {
        const data = await request.json();
        console.log(data);
        const { name, email } = data
        const id = parseInt(params.id);
 
        const updatedUser = await prisma.user.update({
            where: { id },
            data: {
                name,
                email
            }
        });
        return NextResponse.json(updatedUser);
    } catch (error) {
        console.log("Error updating user:", error)
        return NextResponse.error("Internal Server Error", 500)
    }
}
 
export async function DELETE(request, { params }) {
    try {
        const id = parseInt(params.id);
        const deleteUser = await prisma.user.delete({
            where: { id }
        });
        return NextResponse.json(deleteUser);
    } catch (error) {
        console.error("error deleting user:", error);
        return NextResponse.error("Internal server Error", 500);
    }
}
run C:\nextjs>npm run dev

Related Post