[toy blog service] 각페이지를 어떻게 렌더링할지... + json으로 가짜 서버 만들기
페이지를 어떻게 렌더링할지 고민하는 중
- Intro page: Static 하게 고정될거라 Static Generation이 맞다고 판단
- Index page: 최신글과 트렌딩을 보여줘야하는데, 그렇기 때문에 업데이트는 필요하지만 Incremenatl Static Regeneration으로도 충분할 것으로 판단(일정시간지나고 나서 regeneration 하도록)
- username/write page: 글을 작성하고 수정하는 화면인데, 작성 화면 포맷 자체는 Static하게 생성하되, 수정인 경우 Client Side에서 글을 fetching 해와도 충분할 것으로 생각
- username/index page 과 username/[id] page: 개인 블로그의 메인화면과, 조회하는 글이 보이는 화면인데, 종종 변화는 있을 것이지만 변화가 항상 있는 것은 아니라 ServerSide Rendering 이나, Incremental Static Regeneration 중에 고민중인데, preview mode라는것도 알아보기로 생각중
- Preveiw Mode란
To solve precisely this problem, Next.js has a nifty feature called Preview Mode. You can set up an API route to make content editors authenticate, and from that moment, only for their requests, Next.js will switch pre-rendering strategy and start calling getStaticProps functions for every request.
www.datocms.com/blog/live-preview-with-next-js
Tutorial: how to get real-time draft previews with Next.js and DatoCMS
Discover DatoCMS, our headless CMS for websites of any size.
www.datocms.com
JSON으로 가짜 서버 만들기
나는 Next.js에 익숙해지는게 목표라 프로젝트 초기에는 json으로 db를 대신하고자 한다.
{
"user": {
"hayoung": {
"email": "hayoung0.lee@gmail.com",
"password": 1234
},
"Jiyeon": {
"email": "jiyeon@gmail.com",
"password": 1234
}
},
"contents": {
"hayoung": [
{
"id": 0,
"title": "hayoung-1",
"contents": "something something Contents"
},
{
"id": 1,
"title": "hayoung-1",
"contents": "something something Contents"
},
{
"id": 2,
"title": "hayoung-1",
"contents": "something something Contents"
}
],
"jiyeon": [
{
"id": 0,
"title": "jiyeon-1",
"contents": "something something Contents"
},
{
"id": 1,
"title": "jiyeon-1",
"contents": "something something Contents"
},
{
"id": 2,
"title": "jiyeon-1",
"contents": "something something Contents"
}
]
}
}
파일은 이렇게 생겼다. User데이터랑 User에 따른 컨텐츠 정도가 필요할 것 같아서 이렇게 구성했다.
사용하는 방법은 Login API를 통해서 살펴보자
localhost:3000/api/login 요청을 하면 위의 파일에서 처리한다.
import type { NextApiRequest, NextApiResponse } from "next";
import testDB from "../../utils/testDB.json";
export default (req: NextApiRequest, res: NextApiResponse) => {
if (req.method !== "POST") {
res
.status(500)
.json({ message: "Sorry, login api only accepts POST method" });
return;
}
const reqJson = JSON.parse(req.body); // req -> json
if (
testDB.user[reqJson.id] &&
testDB.user[reqJson.id].password === reqJson.password
) {
res.status(200).json({ message: "Login Success" });
} else {
res.status(200).json({ message: "Login Failed" });
}
};
이 파일에서 일어나는 일은 'POST'요청에 대해서 위의 JSON파일과 대조해서 맞는 id랑 password가 들어오면 success, 아니면 fail을 반환하는 것이다.
const r1 = await fetch("http://localhost:3000/api/login",
{method: 'POST',
body: JSON.stringify({id: 'hayoung', password: 1234})
})
const response = await r1.json()
console.log(response)
이 요청을 통해서 확인해 볼 수 있다(id는 JSON데이터에서 USER의 키와 대응하고, password는 해당 키에 대응하는 객체의 password에 대응한다.
좌측은 localhost:3000/api/login으로 get 요청시에 에러메시지를 보내는 것이고, 콘솔에서 post요청을 보내서 확인하면 된다는 것을 알 수 있다.
후기
DB를 직접 구성하기 전에 화면 개발을 집중하기 위해서 간단하게 JSON데이터를 기반으로 API를 구현해보았다. 뒤의 포스트에서는 fs 모듈을 기반으로 JSON데이터에 접근하도록 수정하도록 했다.