카테고리 없음

[코드잇] Next.js API 와 Mongo DB

P1su 2024. 11. 17. 22:06

API 라우트 만들기

api폴더에 js 파일을 만든다. 이 파일이 곧 엔드포인트가 된다.

//short-links
export default function handler(req, res) {
  res.send('안녕 API');
}

이후 /api/short-links 경로로 리퀘스트가 들어왔을 때 실행된다. request 와 response 를 통해서 api 연결을 다룰 수 있다.

 

request 객체를 통하여 body 값, method 종류 등을 확인할 수 있다. 

response 객체를 통해서 status, send 메소드 등으로 상태값 등을 확인할 수 있다. 

export default function handler (req, res) {
  switch (req.method) {
    case 'POST':
      res.status(201).send({
        title: '위키피디아 Next.js',
        url: '',
      });
      break;
    case 'GET': 
      res.send([
        {
          id: 1,
          title: 'dd',
        },
        {
          id: 2,
          title: 'cc',
        },
      ]);
      break;
    default:
      res.status(404).send();
  }
}

Mongo DB

데이터베이스 연동

mongooes connection 을 하나만 만들기 위해서 안전한 코드를 dbConnect.js 에 작성한다.

import mongoose from 'mongoose';

const MONGODB_URI = process.env.MONGODB_URI;

if (!MONGODB_URI) {
  throw new Error(
    'Please define the MONGODB_URI environment variable inside .env.local'
  );
}

/**
 * Global is used here to maintain a cached connection across hot reloads
 * in development. This prevents connections growing exponentially
 * during API Route usage.
 */
let cached = global.mongoose;

if (!cached) {
  cached = global.mongoose = { conn: null, promise: null };
}

이때 mongo db에서 발급받은 데이터베이스에 대한 키값은 .env.local 파일에 작성해둔다. 

모델 만들기

데이터에 대한 일종의 틀이라고 할 수 있다.

먼저 스키마를 생성한다. 스키마는 모델의 구조와 프로퍼티 등을 설정한다.

import mongoose from 'mongoose';

const shortLinkSchema = new mongoose.Schema(
  {
    title: { type: String, default: '' },
    url: { type: String, default: '' },
    shortUrl: { type: String, default: '' },
  },
  {
    timestamps: true,
  }
);

const ShortLink =
  mongoose.models['ShortLink'] || mongoose.model('ShortLink', shortLinkSchema);

export default ShortLink;

model의 첫번째 아규먼트로 보내는 것이 모델의 이름이다.

도큐먼트 생성 조회

create 함수를 통해서 데이터를 생성할 수 있다.

case 'POST':
  const newShortLink = await ShortLink.create(req.body);
  res.status(201).send(newShortLink);
  break;

기본적으로 req.body 는 스키마와 맞지 않는 데이터는 무시한다.

HTTP/1.1 201 Created
ETag: "efupqg1fpr4x"
Content-Type: application/json; charset=utf-8
Content-Length: 177
Vary: Accept-Encoding
Date: Thu, 14 Nov 2024 17:15:12 GMT
Connection: close

{
  "title": "codeit",
  "url": "<https://codeit.kr>",
  "shortUrl": "",
  "_id": "6736302069ff7470ccbdaa47",
  "createdAt": "2024-11-14T17:15:12.590Z",
  "updatedAt": "2024-11-14T17:15:12.590Z",
  "__v": 0
}

기본적으로 id 값을 생성해서 제공해준다.

import dbConnect from '@/db/dbConnect';
import ShortLink from '@/db/models/ShortLinks';

export default async function handler(req, res) {
  await dbConnect();
  const { id } = req.query;

  switch(req.method) {
    case 'PATCH':
      res.send('ShortLink 수정');
      break;
    
    case 'GET':
      const shortLink = await ShortLink.findById(id);
      res.send(shortLink);
      break;
    
    default:
      res.send();
      break;
  }
}

find 함수를 통해서 여러가지 값들을 조회할 수 있다.

    case 'GET': 
      const shortLinks = await ShortLink.find({});
      res.send(shortLinks);
      break;

수정 삭제

수정은 findByIdAndUpdate 메소드를 사용한다.

첫번째 값으로 id를 업데이트 할 값을 객체로 넘겨준다.

PATCH 메소드와 같이 사용하면 된다.

세번째 아규먼트로 업데이튼 된 도큐먼트를 리턴하기 위해서 true 값을 설정해준다.

import dbConnect from '@/db/dbConnect';
import ShortLink from '@/db/models/ShortLinks';

export default async function handler(req, res) {
  await dbConnect();
  const { id } = req.query;

  switch(req.method) {
    case 'PATCH':
      const updatedLink = await ShortLink.findByIdAndUpdate(id, req.body, { new: true });
      res.send(updatedLink);
      break;
    
    case 'GET':
      const shortLink = await ShortLink.findById(id);
      res.send(shortLink);
      break;
    
    default:
      res.send();
      break;
  }
}

삭제는 DELETE 메소드일 경우, findByIdAndDelete 를 사용한다.

아규먼트로 id 값을 넘겨주면 된다.

보통 데이터를 삭제하고 난 후 상태 코드로 204를 보내주곤 한다.

case 'DELETE':
  await ShortLink.findByIdAndDelete(id);
  res.status(204).send();
  break;
728x90