너무나 쉽게 Express로 만들어 보는 REST API

주수호·2021년 5월 17일

1. shema 정의하기

Nosql 잠깐 찍먹하고 가기
https://118k.tistory.com/852

테이블에 대한 명세가 없기 때문에 아무거나 넣을 수 있다는 것이 장점이지만, 아무가너 넣을 수 있다는 것 또한 단점이 된다. 그래서 moongoose와 같이 shema의 형태를 지원하여, 이 형태를 기준으로 document데이터를 관리한다.

확실히 관계형 데이터베이스보다 접근성 하나는 끝내주게 좋은 것 같다.

Sample이라는 이름의 schema만들기


import mongoose from 'mongoose';

const Schema = mongoose.Schema;

const SampleSchema = Schema(
  {
    Name: String,
    Shape: String,
  },
  {
    timestamps: true,
  }
);

SampleSchema.set('toJSON', {
  transform : (doc, result) => {
    return {
      ...result,
      id : result._id
    };
  }
});

SampleSchema.index({ Name: 1 });

export default mongoose.model('Sample', SampleSchema);

장고에서도 MVC중 M을 지정해주고 지원해주는 스타일이 정~말 많았던 것처럼, schema를 지정해 주는것도 정~말 많기 때문에, "필요 할 때 공식문서를 찾아서 쓰기" 스킬을 잘 시전하자

컨트롤러 정의하기

이것도 장고랑 똑같다. 모델을 정의 했으니, 이를 제어하기 위한 컨트롤러가 필요하다. api명세를 하고, 이를 제어하는 컨트롤러를 API로 만들어 보자.

import asyncHandler from 'express-async-handler';
import Sample from '../models/Sample';

// @route   GET /api/sample
// @access  public
const getSamples = asyncHandler(async (req, res) => {
  try {
    const getSample = await Sample.find().lean();
    res.status(200).json(getSample)
  } catch (err) {
    console.log(err);
    res.status(400)
    throw new Error('cannot-find-')
  }
})

// @route   POST /api/sample
// @access  private
const createSample = asyncHandler(async (req, res) => {
  const { title, url } = req.body
  try {
    const newSample = await new Sample({
      title,
      url,
    }).save(); //스키마 생성처리 진행
    if (newSample) {
      res.status(201).json({
        title: title,
        url: url,
      })
    }
  }
  catch (err) {
    console.log(err);
    res.status(400)
    throw new Error('error')
  }
})

// @route   POST /api/updateSample/update
// @access  private
const updateSample = asyncHandler(async (req, res) => {
  const { title, url, id } = req.body;
  try {
    const Sample = await Sample.findById(req.body.id)
  
    if (Sample) {
      Sample.title = title
      Sample.url = url
  
      const updatedSample = await Sample.save()
      res.json(updatedSample)
    } else {
      res.status(404)
      throw new Error('Sample not found')
    }
  }
  catch (err) {
    console.log(err);
    res.status(400)
    throw new Error('error')
  }
})

export {
  getSamples,
  createSample,
  updateSample,
}

기본적인 컨트롤러 또한 정의를 했으니, 이제 route에 등록해 주는 작업이 필요하다

import express from 'express'
const SampleRoutes = express.Router()
import {
  getSamples,
  createSample,
  updateSample,
} from '../controllers/Sample'
const auth = require('../middlewares/auth');

SampleRoutes.route('/sample').get(auth.checkCookieAuth, getSamples).post(createSample);

SampleRoutes.route('/sample/update').post(updateSample);

module.exports = SampleRoutes;

상위를 보면 매우 직관적으로 처리를 할 수 있다.

당연히 api를 요청하기 위한 기본적으로 인증이 완료가 되어져 있는 상태를 체크하기 위해서 처리해주어야 하는 부분이 필요하다.

예시로 route에 get호출시에 (auth.checkCookieAuth)를 붙여 놓았는데, 이를 확인해보자.

.../middlewares/auth.js

import jwt from 'jsonwebtoken'
import asyncHandler from 'express-async-handler'
const checkCookieAuth = asyncHandler(async (req, res, next) => {
  let token
  try {
    token = req.cookies.token;
    const decoded = jwt.verify(token, process.env.SECRET)
    if (decoded.id === undefined) {
      console.log('something went wrong with the jwt');
    }
    next()
  } catch (error) {
    console.error(error)
    res.status(401)
    throw new Error('Not authorized, token failed')
  }

  if (!token) {
    res.status(401)
    throw new Error('Not authorized, no token')
  }
})

exports.checkCookieAuth = checkCookieAuth

이렇게 아주 기본적인 api개발이 끝났다.

profile
항상 준비하는 엔지니어

0개의 댓글