[copy airbnb] 5.列表创建步骤(描述和价格,列表创建 POST 路由)

本章主要的知识点是在nextjs项目中如何创建api服务(路由)

Next.js的API路由是基于文件系统的,即在/pages/api目录下的文件将对应于相应的API路径。所以:http://localhost:3000/api/listings 在目录中的映射就为:

src/app/api/listings/route.ts



import { NextResponse } from "next/server";
import prisma from "@/app/libs/prismadb";
import getCurrentUser from "@/app/actions/getCurrentUser";

export async function POST(request: Request) {
    const currentUser = await getCurrentUser();
    if(!currentUser){
        return NextResponse.error();
    }



    const body = await request.json();
    const {
        title,
        description,
        imageSrc,
        category,
        roomCount,
        bathroomCount,
        guestCount,
        location,
        price
    } = body;
    const listing = await prisma.listing.create({
        data: {
            title,
            description,
            imageSrc,
            category,
            roomCount,
            bathroomCount,
            guestCount,
            locationValue:location.value,
            price:parseInt(price,10),
            userId:currentUser.id
        }
    });

    return NextResponse.json(listing);
}
 

这样一个listing就能记录完成了,当然具体的数据库交互是由prisma进行代理的。

2人评论了“[copy airbnb] 5.列表创建步骤(描述和价格,列表创建 POST 路由)”

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部