0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【備忘録】Next.jsのAppRouterでのAPIについて(Prismaを使用)

Last updated at Posted at 2023-12-26

背景

Prismaを使ってDBを操作するのにNext.jsでAPIを使うため

階層
|- app
    |- api
        |- create
        |   |- route.ts
        |- update
            |- route.ts

※以下prismaについては説明を省かせて頂きます

基本の形(諸説あり)

route.ts
import { NextRequest, NextResponse } from 'next/server'

export const GET or POST = async(req: NextRequest, res: NextResponse) => {
    try{
        return NextResponse.json({ message: "Success" }, { status: 200 })
    }catch(err){
        return NextResponse.json({ message: "Error", err }, { status: 500 })
    }
}

何かしらデータを送った時

※送り方は各々でお調べください

route.ts
import prisma from 'prismaClientの位置'
import { NextRequest, NextResponse } from 'next/server'

export const GET or POST = async(req: NextRequest, res: NextResponse) => {
    try{
        // ここにデータが入っています
        const body = await req.json()
        // idなどでwhereしたい場合に使えます
        const user = await prisma.user.findUnique({
            where: {
                id: body.id
            },
        })
        return NextResponse.json({ message: "Success", user }, { status: 200 })
    }catch(err){
        return NextResponse.json({ message: "Error", err }, { status: 500 })
    }
}

まとめ

まだ完全に理解はしていませんがおおよそ使えるくらいにはなったと思い、備忘録として残して置きます。間違いやアドバイスなどあればお願いします。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?