Elice SW engineer - TIL day 28

Circlewee·2022년 5월 11일
0

Elice SW 2 TIL

목록 보기
25/31

1. Express

1.1 Middleware

  • Express.js 동작의 핵심
  • HTTP 요청과 응답 사이에서 단계별 동작을 수행해주는 함수
  • request, response, next를 인자로 사용해 함수 작성
const auth = (req, res, next) => {
  if (!isAdmin(req)) {
    res.send('Not Authorized');
   	return ;
  }
  next();
}
  • req, res 객체를 통해 요청과 응답을 처리하거나 next()를 통해 다음 미들웨어를 호출해야함
    호출하지 않을시 미들웨어 사이클이 멈춤
router.use(auth); // 3

router.get('/', (req, res, next) => { // 4
  res.send('Hello Router');
});

app.use((req, res, next) => { // 2
  if (!isAdmin(req)) {
    next(new Error('Not Authorized'));
   	return ;
  }
  next();
});

app.use('/admin', router); // 1

app.use((err, req, res, next) => { // 만약 2번에서 오류가 발생했다면
  res.send('Error occurred');
});
  • 1,2는 application middleware, 3, 4는 router middleware다.
    진행 순서는 1, 2, 3, 4다.
  • 2번에서 오류가 발생돼 next()에 인자를 주고 실행하면 자동으로 맨 아래 미들웨어(오류처리 미들웨어)가 실행된다.
const auth = (memberType) => {
  return (req, res, next) => {
  	if (!checkMember(req, memberType)) {
    	next(new Error(`member not ${memberType}`));
   		return ;
  	}
  	next();
  }
}
  • 함수형 미들웨어
  • 함수 실행시 미들웨어의 동작이 인자로 주어지는 것에 의해 결정된다. 동일한 로직에 설정 값만 다르게 미들웨어를 사용하고 싶을 경우에 활용

1.2 요청 응답

router.post('/make-user', async (req, res) => {
  const user = new User({
    username: req.body.username,
    password: req.body.password,
  });

  await user.save((err, user) => {
    if (err) {
      res.sendStatus(500);
    } else {
      res.sendStatus(200);
    }
  });
});
  • 인자로 넘겨준 URI로 POST요청이 들어오면 요청을 처리할 미들웨어이다.
  • req.body로 클라이언트에서 요청에 추가한 body에 접근할 수 있다.
  • PUT, DELETE, GET을 각각 메소드로 처리할 수 있지만 PUT, DELETE는 post로 처리해도 mongoose메소드를 통해 똑같이 동작하게 만들 수 있어 잘 사용하지 않는다.

2. MongoDB

  • Nosql의 대표적인 db
  • 대용량처리에 압도적으로 유리(성능)
  • 다만 데이터를 찾는 것에 취약하다(고유 key값을 활용하기 어려움)
  • 각각 DB의 관계를 생각하지 않고 설계할 수 있으며 JSON에 훨씬 친화적이다.

2.1 Mongoose

  • server와 mongoDB사이의 징검다리 역할
  • 여러 메소드들을 통해 데이터를 쉽게 저장, 찾을 수 있도록 하고 연결을 지원한다.
// connection 정보는 별도의 json이나 dotenv를 이용해 저장해둔다. 안 그러면 보안 위험!!!!
const url = 'mongodb://' + connect.username + ':' + connect.password + '@' +
  connect.url + '/' + connect.dbname;

// db connection
const dbconnect = () => {
  mongoose.connect(url, (error) => {
    if (error) {
      console.log('mongodb connect error', error);
    } else {
      console.log('mongodb-connect-success');
    }
  });
};

2.1.1 Schema

  • DB에 데이터를 삽입하기 위한 데이터의 요소를 정의
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const book = new Schema({
  bookname: { type: String, required: true } // 이 밖에도 boolean, default등을 지정할 수 있다.
  author: String,
  price: { type: Number, default: 0 },
  publish: Date
})
// 'book'은 사용할 collection의 이름이다. mongoDB가 자동으로 s를 추가한다. => books
const bookData = mongoose.model('book', book);
module.exports = bookData;

2.1.2 post

  • schema의 형태를 이용해 데이터를 정의해서 DB에 삽입할 수 있다.
const BookSchema = require('../models/book'); // 위에서 exports한 mongoose.model
...
router.post('/addbook', (req, res) => {
  const bookname = req.body.bookname;
  const author = req.body.author;
  const price = req.body.price;
  const publishdate = req.body.publish_date;

  let bookData = new BookSchema({ // class처럼 사용
    // 이 아래는 BookSchema의 key 값과 같아야한다.(대소문자까지)
    bookname,
    author,
    price,
    publishdate,
  });
  bookData.save(); // 이 부분이 DB에 위에서 작성한 bookData를 삽입하는 코드
  res.redirect('/expost');
});

2.1.3 find를 활용한 찾기

  • find() method를 이용해 원하는 데이터를 찾아 응답한다.
router.get('/bookinfo/:id', (req, res) => {
  const authorname = req.params.id; // uri parameter

  BookSchema.find({ author: authorname })
    .then((result) => {
      return res.json(result);
    })
    .catch((err) => console.log(err));
});
profile
공부할 게 너무 많아요

0개의 댓글

관련 채용 정보