본문 바로가기

Node.js

Statesairline-Server

//app.js
const express = require('express'); //express 모듈 불러오기
const cors = require('cors'); //cors미들웨어 불러오기
const app = express(); //express모듈을 이용하여 서버를 만든다. express는 함수. return된 값은 application 객체

// 모든 서버는 요청을 받을수 있는 포트 번호를 필요로 합니다.

// HTTP server의 표준 포트는 보통 80 번 이지만, 보통 다른 서버에서 사용중이기 때문에 접근할 수 없습니다.
// 따라서 우리는 보통 테스트 서버 포트로 3000, 8080, 1337 등을 활용합니다.

// PORT는 아파트의 호수와도 같습니다. 서버로 요청을 받기 위해서는 다음과 같이 포트 번호를 설정 합니다.
// (* 때에 따라 다른 포트번호를 열고 싶다면, 환경 변수를 활용 하기도 합니다.)
const port = 3001;

const flightRouter = require('./router/flightRouter');
const bookRouter = require('./router/bookRouter');
const airportRouter = require('./router/airportRouter');
// 셋다 모듈 불러오는 것.

app.use(cors()); //모든 요청에 대해 CORS허용
app.use(express.json()); //모든 JSON형태의 request body를 parsing하기. 
//express로 웹 서버를 만들 때, JSON형태의 request body를 받았을 때, 요청값을 제대로 받아오지 못하는 문제 발생.
//express.json()모듈을 사용하면 JSON형태의 request body를 잘 받아올 수 있다.

app.use('/flight', flightRouter); // /flight 모든 요청 시, flightRouter함수 실행
app.use('/book', bookRouter); // /book 모든 요청 시, bookRouter함수 실행
app.use('/airport', airportRouter); // /airport 모든 요청 시, airportRouter함수 실행

app.get('/', (req, res) => {
  res.status(200).send('Welcome, States Airline!');
}); //http://localhost:3001/ get요청 시, status code : 200 & 화면에 'Welcome, States Airline!'

app.use((req, res, next) => {
  res.status(404).send('Not Found!');
});

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send({
    message: 'Internal Server Error',
    stacktrace: err.toString()
  });
});

app.listen(port, () => {
  console.log(`[RUN] StatesAirline Server... | http://localhost:${port}`);
});

module.exports = app;

 

 

 

[Case : flightRouter]

//flightRouter.js
const { findAll, findById, update } = require('../controller/flightController');
const express = require('express');
const router = express.Router();

router.get('/', findAll); // /flight get요청시, findAll함수 실행
// /flight뿐만 아니라 /flight?..이렇게 queryString오는것도 다 포함된다.

router.get('/:id', findById); // /flight/.... get요청시, findById함수 실행

router.put('/:id', update); // /flight/.... put요청시, update함수 실행

module.exports = router;

1.  GET /flight?departure_times=2021-12-03T12:00:00&arrival_times=2021-12-03T12:00:00를 입력하면 조건에 해당하는 객체를 리턴해야 합니다.

/flight?뒤에 오는 것들 : req.query

departure_times=.. <-- req.query.departure_times

arrival_times=... <-- req.query.arrival_times

 

이 경우는  router.get('/', findAll)에 속한다. 

req.query.departure_times와 req.query.arrival_times가 존재하므로

flightList의 배열 중, departure_times와 동일한 것 && arrival_times와 동일한 것.

 

2. GET /flight?departure=CJU&destination=ICN 을 입력하면 조건에 해당하는 객체를 리턴해야 합니다.

req.query.departure === CJU

req.query.destination === ICN

 

 

3. GET /flight/{:id} 요청의 응답 객체는 `uuid, departure, destination, departure_times, arrival_times`를 포함해야 합니다.

이 경우는 router.get('/:id', findById)에 속한다. 

'/:id'이기 때문에 사용할 때는 req.params.id로 해야!

 

ex: /user/:name이면 req.params.name로 해야한다.

GET /user/tj이면 req.params.name

=== tj

//flightController.js
const flights = require('../repository/flightList');

module.exports = {
  // [GET] /flight
  // 요청 된 departure_times, arrival_times, destination, departure 값과 동일한 값을 가진 항공편 데이터를 조회합니다.

  findAll: async (req, res) => {
    if (req.query.departure_times !== undefined && req.query.arrival_times !== undefined) {
      console.log(req.query.departure_times); //2021-12-03T12:00:00 이 값이 나온다.
      const list = flights.filter((item) => {
        return (item.departure_times === req.query.departure_times) && (item.arrival_times === req.query.arrival_times)
      }); //flights 배열(즉, flightList)요소 중에서 departure_times의 value와 req.query.departure_times의 값과 같고,
    //arrival_times가 req.query.arrival_times 같은 요소. true인 요소들만 뺀 배열 === list
      return res.status(200).json(list); //그 배열을 status code : 200 & JSON형태로 전달.
    }

    if (req.query.departure !== undefined && req.query.destination !== undefined) {
      console.log(req.query.departure);
      const list = flights.filter((item) => {
        return (item.departure === req.query.departure) && (item.destination === req.query.destination)
      }); //flight(즉,flightList)요소 중에서, departure의 value가 req.query.departure의 값과 같고,
      //destination의 값과 req.query.destination의 값과 같은 요소만 필터링한 배열 === list
      return res.status(200).json(list);//status code : 200 & list배열을 JSON형태로 전달. 
    }
    return res.json(flights); // /flight뒤에 req.query가 없거나, departure_times, arrival_times, departure, destination값이 없을 때
  },
  
  // [GET] /flight/{:id}
  // 요청 된 id 값과 동일한 uuid 값을 가진 항공편 데이터를 조회합니다.
  findById: async (req, res) => { 
    if (req.params.id !== undefined) {
      console.log(req.params.id);
      const list = flights.filter((item) => {
        return item.uuid === req.params.id;
      });//flights배열 중, uuid의 값과 req.params.id의 값이 동일한 것 필터링 한 배열 === list
      return res.status(200).json(list);// status code:200 && list배열 json형태로 보낸다.
    }
  }
};

 

//flightLIst
module.exports = [
  {
    uuid: 'af6fa55c-da65-47dd-af23-578fdba40bed',
    departure: 'ICN',
    destination: 'CJU',
    departure_times: '2021-12-02T12:00:00',
    arrival_times: '2021-12-03T12:00:00'
  },
  {
    uuid: 'af6fa55c-da65-47dd-af23-578fdba40byd',
    departure: 'ICN',
    destination: 'PUS',
    departure_times: '2021-12-03T12:00:00',
    arrival_times: '2021-12-03T12:00:00'
  },
  {
    uuid: 'af6fa55c-da65-47dd-af23-578fdba48bed',
    departure: 'ICN',
    destination: 'CJU',
    departure_times: '2021-12-03T12:00:00',
    arrival_times: '2021-12-04T12:00:00'
  },
  {
    uuid: 'af6fa55c-da65-47dd-af23-578fdbr40bed',
    departure: 'ICN',
    destination: 'CJU',
    departure_times: '2021-12-03T12:00:00',
    arrival_times: '2021-12-04T12:00:00'
  },
  {
    uuid: 'af6fa55c-da65-47dd-af23-578fd7a40bed',
    departure: 'ICN',
    destination: 'BKK',
    departure_times: '2021-12-02T12:00:00',
    arrival_times: '2021-12-03T12:00:00'
  },
  {
    uuid: 'af6fa55c-da65-47dd-af23-578fdba40bod',
    departure: 'ICN',
    destination: 'CJU',
    departure_times: '2021-12-02T12:00:00',
    arrival_times: '2021-12-03T12:00:00'
  },
  {
    uuid: 'af6fa55c-da65-47dd-af23-578fdba44bed',
    departure: 'ICN',
    destination: 'CJU',
    departure_times: '2021-12-03T12:00:00',
    arrival_times: '2021-12-03T12:00:00'
  },
  {
    uuid: 'af6fa55c-da65-47dd-af23-578fdba42bed',
    departure: 'CJU',
    destination: 'ICN',
    departure_times: '2021-12-03T12:00:00',
    arrival_times: '2021-12-04T12:00:00'
  },
  {
    uuid: 'af6fa55c-da65-47dd-af23-578fdba41bed',
    departure: 'CJU',
    destination: 'ICN',
    departure_times: '2021-12-03T12:00:00',
    arrival_times: '2021-12-03T12:00:00'
  },
  {
    uuid: 'af6fa55c-da65-47dd-af23-578fdba99bed',
    departure: 'CJU',
    destination: 'ICN',
    departure_times: '2021-12-03T12:00:00',
    arrival_times: '2021-12-04T12:00:00'
  },
  {
    uuid: 'af6fa55c-da65-47dd-af23-578fdba50bed',
    departure: 'CJU',
    destination: 'ICN',
    departure_times: '2021-12-02T12:00:00',
    arrival_times: '2021-12-03T12:00:00'
  }
];

 

 

[Case : bookRouter]

1. POST /book 요청시, flight_uuid, name, phone 데이터가 객체로 저장되어야 합니다. 

app.use('/book', bookRouter); // /book 모든 요청 시, bookRouter함수 실행

 

app.js의 코드에 따라 bookRouter함수 실행

//bookRouter.js
const { findById, create, deleteById } = require('../controller/bookController');
const exress = require('express');
const router = exress.Router();

router.get('/', findById); // /book(queryString)으로 get요청 시 findById함수 실행 

router.post('/', create); // /book(queryString)으로 post요청 시 create함수 실행 

router.delete('/', deleteById); // /book(queryString)으로 delete요청 시 deleteById함수 실행 

module.exports = router;

POST /book 즉, POST요청이니 create함수 실행

//bookController.js
const flights = require('../repository/flightList');
// 항공편 예약 데이터를 저장합니다.
let booking = [];

module.exports = {
  // [GET] /book 요청을 수행합니다.
  // 전체 데이터 혹은 요청 된 flight_uuid, phone 값과 동일한 예약 데이터를 조회합니다.
  findById: async (req, res) => {
    // /flight?departure_times=2021-12-02T12:00:00&arrival_times=2021-12-03T12:00:00
    // /flight?departure=ICN&destination=CJU 
    if (req.query.flight_uuid !== undefined) {
      const list = booking.filter((reservation) => {
        return (reservation.flight_uuid === req.query.flight_uuid)
      });
      return res.status(200).json(list);
    }

    if (req.query.phone !== undefined) {
      const list = booking.filter((reservation) => {
        return (reservation.phone === req.query.phone)
      })
      return res.status(200).json(...list);
    }

    return res.status(200).json(booking);
  },

  // [POST] /book 요청을 수행합니다.
  // 요청 된 예약 데이터를 저장합니다.
  create: async (req, res) => {
    const { flight_uuid, name, phone } = req.body; //reqeust body에서 구조분해할당으로
    //flight_uuid, name, phone의 value를 따로 가져오는 것. 
    booking.push({ flight_uuid, name, phone });//그 값들을 booking배열에 객체 형태로 넣기. 
    //그냥 booking.push(req.body) 이렇게 해도 테스트 통과 됨.
    return res.status(201).json({ message: 'Create success!' });
  },

  // [DELETE] /book?phone={phone} 요청을 수행합니다.
  // 요청 된 phone 값과 동일한 예약 데이터를 삭제합니다.
  deleteById: async (req, res) => {
    if (req.query.phone !== undefined) {
      booking = booking.filter((book) => { return book.phone !== req.query.phone })
    }
    return res.status(200).json(booking);
  }
};

 

create함수를 보면 booking이라는 배열에 flight_uuid, name, phone의 값이 들어있는 req.body를 booking이라는 배열에 push함.

** 'request body'에는 'key-value'의 데이터가 담긴 객체 프로퍼티이다. 

그래서 req.body ==={flight_uuid: .., name: .., phone: ..} 이렇게 되어 있을 것.

 

create: async (req, res) => {
    const { flight_uuid, name, phone } = req.body; //reqeust body에서 구조분해할당으로
    //flight_uuid, name, phone의 value를 따로 가져오는 것. 
    booking.push({ flight_uuid, name, phone });//그 값들을 booking배열에 객체 형태로 넣기. 
    //그냥 booking.push(req.body) 이렇게 해도 테스트 통과 됨.
    return res.status(201).json({ message: 'Create success!' });
  }

 

 

2. GET /book?flight_uuid=af6fa55c-da65-47dd-af23-578fdba50bed 요청은 특정 항공편에 대한 모든 예약 객체를 반환해야 합니다.

req.query.flight_uuid === af6fa55c-da65-47dd-af23-578fdba50bed

아래 코드에 의해 findById함수 실행. 

router.get('/', findById); // /book(queryString)으로 get요청 시 findById함수 실행
  findById: async (req, res) => {
    if (req.query.flight_uuid !== undefined) {
      const list = booking.filter((reservation) => {
        return (reservation.flight_uuid === req.query.flight_uuid)
      });
      return res.status(200).json(list);
    }

booking 배열에서 flight_uuid의 value가 req.query.flight_uuid의 값과 동일한 요소만 필터링해서 list변수에 담는다.

그리고, 그 list를 JSON형태로 내보낸다. 

 

3. GET /book?phone=010-1234-5678 요청은 번호에 해당하는 예약 내역을 반환해야 합니다.

req.query.phone === 010-1234-5678

이것도 /book(queryString) get요청이니 findById함수 실행.

  findById: async (req, res) => {
    if (req.query.phone !== undefined) {
      const list = booking.filter((reservation) => {
        return (reservation.phone === req.query.phone)
      })
     // const [{ flight_uuid, name, phone }] = list; 구조분해할당
     // return res.status(200).json({ flight_uuid, name, phone }); 예약내역객체자체를 내보냄
      return res.status(200).json(...list);
    }
    return res.status(200).json(booking);
  }

booking 배열에서 phone의 value가 req.query.phone의 값과 동일한 요소만 필터링해서 list변수에 담는다.

그리고, 그 list배열의 예약내역를 JSON형태로 내보낸다. 

 

4.  Delete /book?phone=010-1234-5678 요청을 하면 예약 목록에서 파라미터 phone에 해당하는 데이터가 삭제되어야 합니다.

req.query.phone === 010-1234-5678

아래 코드에 의해 deleteById함수 실행

router.delete('/', deleteById); // /book(queryString)으로 delete요청 시 deleteById함수 실행

 

  deleteById: async (req, res) => {
    if (req.query.phone !== undefined) {
      booking = booking.filter((book) => { return book.phone !== req.query.phone })
    }
    return res.status(200).json(booking);
  }

booking 배열에 phone의 value와 req.query.phone이 다른 것만 넣은(즉, 같은건 빼낸다) 배열을 다시 booking배열에 할당한다.

그리고 그 배열을 JSON형태로 내보낸다. 

'Node.js' 카테고리의 다른 글

Node.js에 대하여  (0) 2023.11.26
package.json에 있는 "dependencies"의 역할 및 npm install(ft. 모듈이란?)  (0) 2021.11.20
mininode-server with Express  (0) 2021.09.24
mini-node server  (0) 2021.09.23
fs.readFile 메소드  (0) 2021.09.21