[항해99] 36일차 API 짜기

IT/Bootcamp 항해99|2021. 7. 13. 00:28

항해 99

 

36일차: 

API설계도를 보고 각자 맡은 api설계를 하기로했다.

몇번 프론트분들과 얘기를해서 중간중간 변경도 하고, 처음보다 변경사항이 꽤있는것같다.

 

 

1. req.param  vs req.quary 

 

 

 

2.  seqeuilizer + express API

더보기

 

   findOne  : 값에 맞는것중 하나만 찾아온다.  (첫번째로 찾은것만 가져오는걸까?)

 

  작성자 (nickname) 가 쓴 글을 가져와서 수정한다. 

app.post('/ads', async (req,res)=>{
  const {title,category,content,participant,maxPeople} = req.body
  console.log(req.body)
  const nickname = "gil"
  const user = await User.findOne({where: {nickname: nickname}})
  console.log(user)

   try {
  const newPost = await Ad.create({
    title,
    nickname,
    category,
    content,
    participant,
    maxPeople
  })
  user.addAd(newPost)
  res.send("okay")
  } catch (error) {
    res.send("errror msg")({
      errorMeassage: "Can not post this"
    })
  }
})

   findAll 

찾고자하는 값과 같으면 다가져온다.

 

이 api 는 get을이용해서  req.query를사용한다

?category=potato 부분이 쿼리이고,   /ads/:id로 해서 param으로 가져올수있지만, REST 하게 api를 짠다면 

get + qeury 로 가져오는게 더 알맞은방식이다.

 

그래서 quary가 없다면 -> 그냥 모든 포스트를 가져오고

quary가잇다면 필터기능해서 해당하는 카테고리의 글들을 가져온다.

app.get('/ads', async (req, res) => {
  const { category } = req.query;
  if (category){
    const ads = await Ad.findAll({ where:{category:category }}); 
    res.json(ads)
  }
  else{ const ads = await Ad.findAll();
    console.log(ads);
    res.json(ads)
  }

});

 

   update

찾아서 값을 update해준다

adId로 글을찾아서 그 글의 title 과 content 를 변경해준다.

app.put("/ads/:adId", async(req,res)=>{

  const {adId} = req.params
  const {title, content} = req.body
  const updatedAd = await Ad.update({ title:title, content:content},{
    where:{
      id :adId,
    }
  })
  res.send(updatedAd)
})

   destroy 

 

adId로 찾아서 삭제해준다!

app.delete('/ads/:adId', async (req,res)=>{
  const {adId} = req.params
  const user = await Ad.destroy({where: {id : adId}})
  res.status(200).send("successfully deleted")
  
})

 

여기서 중요한점은 앞서말한  get->  req.query로받아오기  post. put, delete는 :id로 req.param으로 받아올수있다. 

 

 

 

 

3. junction model pattern 

 

 

ORM은 언제나 어렵다.

 

서로 두 모델이 has many의 관계일때,  many to many관계일때,  두 모델 중간에 junction이 필요하다.

 

https://khalilstemmler.com/articles/sequelize-tags-junction-pattern/

 

Junction Model Pattern: Many-to-Many - Sequelize | Khalil Stemmler

Many-to-many is a common modeling relationship between two entities. Here's one way to handle it with the Sequelize ORM.

khalilstemmler.com

 

 

 

4.   

관심사 분리 / sepeartion of concern ;

 

이부분은 design pattern?  design philasphy부분인것같은데, 

프로젝트의 폴더 구조, 파일구조 등을 설계할때 쓰이는 컨셉인것같다.

관심사 분리를 이용하면 프로그램의 설계, 디플로이, 이용의 일부 관점에 더 높은 정도의 자유가 생긴다. 이 가운데 일반적인 것은 코드의 단순화 및 유지보수의 더 높은 수준의 자유이다. 관심사가 잘 분리될 때 독립적인 개발과 업그레이드 외에도 모듈 재사용을 위한 더 높은 정도의 자유가 있다

 

OOP 수업을들을때 design pattern을 할때배웠던 비슷한 컨셉인것같기도 하다.

 

일단 , 우리 프로젝트에서 이 concept이 적용이 된 부분은 

 

model들이 모두 함수로 export되어서 -> model/index부분에서  모든 모델을 관리해주고  db로 연결을해준다. 

model 들과  db table을 나눠주고  나중에  유지보수가 더 수월하다는걸까 ? (아직까지 확실하게 알고잇는 개념은 아닌것같다) 

그냥 추상화(abstarction?)의 일종이라고 익혀두고 넘어가자.

 

model/index: 

const Sequelize = require('sequelize')
const { config } = require('./../config/config.json')
const Comment = require('./comments')
const Ad = require('./ads')
const User = require('./users')

const sequelize = new Sequelize(config)
const dataTypes = Sequelize.DataTypes

const models = {}

models.sequelize = sequelize
models.User = User(sequelize, dataTypes)
models.Ad = Ad(sequelize, dataTypes)
models.Comment = Comment(sequelize, dataTypes)

models.User.associate(models)
models.Ad.associate(models)
models.Comment.associate(models)

module.exports = models

 

https://ko.wikipedia.org/wiki/%EA%B4%80%EC%8B%AC%EC%82%AC_%EB%B6%84%EB%A6%AC#:~:text=%EC%BB%B4%ED%93%A8%ED%84%B0%20%EA%B3%BC%ED%95%99%EC%97%90%EC%84%9C%20%EA%B4%80%EC%8B%AC%EC%82%AC%20%EB%B6%84%EB%A6%AC,%EC%9D%98%20%EA%B4%80%EC%8B%AC%EC%82%AC%EB%A5%BC%20%ED%95%B4%EA%B2%B0%ED%95%9C%EB%8B%A4.&text=%EA%B4%80%EC%8B%AC%EC%82%AC%20%EB%B6%84%EB%A6%AC%EB%A5%BC%20%EC%9D%B4%EC%9A%A9%ED%95%98%EB%A9%B4,%EC%A0%95%EB%8F%84%EC%9D%98%20%EC%9E%90%EC%9C%A0%EA%B0%80%20%EC%83%9D%EA%B8%B4%EB%8B%A4

반응형

댓글()