prisma 파일 수정
prisma/schema.prisma
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mysql"
url = "mysql://root:13243546@localhost:3306/local_mysql"
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
password String
posts Post[]
matasetting Metasetting[]
}
model Metasetting {
id Int @id @default(autoincrement())
title String
keyword String?
telnum String?
author User @relation(fields: [authorId], references: [id])
authorId Int
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
}
prisma 파일 전체인데 여기서
model Metasetting {
id Int @id @default(autoincrement())
title String
keyword String?
telnum String?
author User @relation(fields: [authorId], references: [id])
authorId Int
}
이 부분이 추가되었다.
자동으로 추가되는 id,
title, keyword, telnum 을 입력하고,
User와 연결되는 authorId 를 저장한다.
마이그레이션 실행
npx prisma migrate dev --name metasetting
// npx prisma migrate dev --name 테이블이름
// npx prisma migrate dev 명령어를 이용하면 날짜로 제작된 폴더가 생성됨
마이그레이션을 실행하여 데이터베이스에 적용한다.
migrate
- 적용되지 않은 최근의 마이그레이션 파일 사용
- 없을 시 새로 생성
- migrate는 데이터 베이스 내용 초기화 (날라간 이유구나..?)
DB 수정 후 저장
수정사항 가져오기
npx prisma db pull
DB 데이터 유지 & 스키마 수정사항 적용
npx prisma db push
migrations 폴더 내부에 spl문이 작성된 걸 확인할 수 있다.
API route 추가
api/metasetting/route.ts 파일 생성하여 api를 추가한다.
import { PrismaClient } from "@prisma/client";
interface RequestBody {
title: string;
keyword: string;
telnum: string;
authorId: number;
}
const client = new PrismaClient();
export async function POST(request: Request) {
const body: RequestBody = await request.json();
const metasetting = await client.metasetting.create({
data: {
title: body.title,
keyword: body.keyword,
telnum: body.telnum,
authorId: body.authorId,
},
});
return new Response(JSON.stringify(metasetting));
}
API 코드 사용
//app/userposts/page.tsx
"use client"; //Client 사이드 로직이라 별도 컴포넌트를 만들고 그 컴포넌트에는 'use client'라고 명시
import { useSession } from "next-auth/react";
import { FormProvider, useForm } from "react-hook-form";
interface HookFormTypes {
_title: string;
_keyword: string;
_telnum: string;
_authorId: Number;
}
function UserPosts() {
const session: any = useSession();
const methods = useForm<HookFormTypes>();
const { register, handleSubmit, getValues, watch } = methods;
const fnSubmit = async () => {
const res = await fetch(
`http://localhost:3000/api/metasetting`,
// `${process.env.NEXT_PUBLIC__NEXTAUTH_URL}/api/adduser`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: watch("_title"),
keyword: watch("_keyword"),
telnum: watch("_telnum"),
authorId: session.data.user.id,
}),
}
);
const metasetting = await res.json();
if (metasetting) {
console.log(metasetting);
return metasetting;
} else {
return null;
}
};
return (
<div className="mx-auto w-full h-full">
<div className="w-[24rem] mx-auto h-auto mt-[10%] border rounded-md border-solid border-slate-200 bg-white">
<main className="px-3 py-6">
<h1 className="text-center text-3xl font-semibold mb-10">정보입력</h1>
<FormProvider {...methods}>
<form onSubmit={handleSubmit(fnSubmit)}>
...
</form>
</FormProvider>
</main>
</div>
</div>
);
}
export default UserPosts;
// `${process.env.NEXT_PUBLIC__NEXTAUTH_URL}/api/adduser`,를
제대로 가져오지 못해 오류가 나고 있는데 이유는 나중에 찾아봐야 한다.
'front > next' 카테고리의 다른 글
next.js 14 aws cloudfront, s3 (client mode) 배포 (0) | 2024.03.06 |
---|---|
SSR - next.js 설치 SSR, CSR의 차이 (0) | 2024.02.15 |
next 간편로그인 (카카오, 네이버) (0) | 2024.01.30 |
next 로그인 커스텀 디자인 (pages signin() 페이지 커스텀 설정 & nextauth이용하여 api 등록) (0) | 2024.01.30 |
next 로그인 토큰 jwt 설정 (middleware - 로그인됐을 때만 사용할 수 있는 페이지 등록 & params설정 & 현재 url 가지고 오기 ) (0) | 2024.01.30 |