728x90
반응형

* git 연동 후 vercel에 등록된 상태로 진행해주세요*

 

1.  Postgres Database 생성

 

Storage -> Create Database 클릭

 

 

 

 

Postgres -> Database 설정

 

- Database Name : 데이터베이스명을 입력합니다.

- Region : 데이터센터의 물리적 위치를 선택합니다. (프로그램이 실행되는 위치와 가까운 장소를 선택할수록 빠른 통신이 가능합니다)

 

 

 

 

2. 프로젝트에 DB 연결

 

생성된 postgres database로 접속후 -> Getting Started -> Connect Project 클릭

 

 

 

 

vercel에 연결되어있는 프로젝트 중 DB에 연결할 프로젝트를 선택합니다.

 

저는 기본설정으로 연결하였습니다.

 

 

 

 

vercel link

vercel env pull .env.development.local

 

vscode로 프로젝트에 접속하여 로컬에서도 postgres를 사용할 수 있도록 설정합니다.

 

* .env.development.local 파일에는 postgres 관련 민감한 정보들이 들어있으니

    git 또는 외부에 공유되지 않도록 주의해야합니다.

 

 

 

 

3. 테이블 생성 및 데이터 추가

 

vercel -> Storage -> 생성한 postgres -> Data -> Query 로 접근

 

아래 쿼리들을 실행하여 데이터를 넣고 테스트 해봅시다.

 

 

CREATE TABLE posts (
    id SERIAL PRIMARY KEY,
    title VARCHAR(255),
    content TEXT,
    author VARCHAR(100)
);

 

해당 쿼리는 게시글 테이블을 생성합니다.

 

INSERT INTO posts (title, content, author) VALUES
    ('첫 번째 게시물', '첫 번째 게시물의 내용입니다.', '홍길동'),
    ('두 번째 게시물', '두 번째 게시물의 내용입니다.', '이순신'),
    ('세 번째 게시물', '세 번째 게시물의 내용입니다.', '강감찬'),
    ('네 번째 게시물', '네 번째 게시물의 내용입니다.', '유관순'),
    ('다섯 번째 게시물', '다섯 번째 게시물의 내용입니다.', '김유신');

 

해당 쿼리는 게시글 테이블에 데이터를 넣습니다.

 

 

 

데이터가 잘 들어왔다면 프로젝트에서 조회해봅시다.

 

 

 

 

4. 데이터 조회하기

npm install @vercel/postgres

 

postgres 데이터를 조회할 수 있는 라이브러리를 설치합니다.

 

 

 

/* /services/posts.ts */

'use server'

import { sql } from "@vercel/postgres";

export interface Posts {
	id : number,
	title : string,
	content : string,
	author : string,
}

export async function getPostsData(): Promise<Posts[]> {
	try {
		const { rows }: { rows: Posts[] } = await sql
			`SELECT id, title, content, author FROM posts;`;
		return rows;
	} catch (error) {
		throw new Error('Failed to fetch posts data');
	}
}

 

조회 쿼리를 통해 직접 게시글 목록을 조회하는 파일입니다.

 

 

/* page.tsx */

'use client'
import { Posts, getPostsData } from "@/services/posts";
import { useEffect, useState } from "react";

const defaultPosts: Posts = {
  id: 0,
  title: "",
  content: "",
  author: "",
};

export default function Page() {
  const [posts,getPosts] = useState<Posts[]>([defaultPosts]);

  useEffect(() => {
    fetchData();
  },[]);

  const fetchData = async () => {
    try {
      const postsData = await getPostsData();
      getPosts(postsData);
    } catch (error) {
      throw new Error('Failed to fetch posts data');
    }
  };

  return (
    <div>
      <div className="overflow-x-auto">
        <table className="min-w-full bg-white">
          <thead>
            <tr>
              <th className="px-6 py-3 bg-gray-100 text-left text-xs leading-4 font-medium text-gray-600 uppercase tracking-wider">제목</th>
              <th className="px-6 py-3 bg-gray-100 text-left text-xs leading-4 font-medium text-gray-600 uppercase tracking-wider">내용</th>
              <th className="px-6 py-3 bg-gray-100 text-left text-xs leading-4 font-medium text-gray-600 uppercase tracking-wider">작성자</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200">
            {posts.map((post)=>(
              <tr key={post.id}>
                <td className="px-6 py-4 whitespace-no-wrap">{post.title}</td>
                <td className="px-6 py-4 whitespace-no-wrap">{post.content}</td>
                <td className="px-6 py-4 whitespace-no-wrap">{post.author}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

 

조회된 데이터가 테이블에 출력될 수 있도록 처리합니다.

 

 

 

 

 

postgres에 쿼리로 넣었던 데이터가 정상적으로 조회되는것을 볼 수 있습니다.

 

 

 

 

DROP TABLE posts;

 

마지막으로 테스트용 테이블인 posts를 삭제하고 프로젝트에 맞게 사용하시면 됩니다.

728x90
반응형

+ Recent posts