section2 stateairline-server

유희준·2023년 4월 6일

section2

목록 보기
12/12

App.js


const express = require('express');  // express 모듈 가져오기 (express = 서버를 만드는 프레임 워크)
const cors = require('cors'); // cors 모듈 가져오기 
const app = express(); //app에 새 인스턴스 할당

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

// 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()); //파싱된 req.body 객체는 application/json 형식의 HTTP 요청 본문(body) 데이터를 JSON 객체로 변환합니다.

app.use('/flight', flightRouter); // 이렇게 설정된 flightRouter는 express 애플리케이션에서 /flight 경로에 대한 요청을 처리합니다.
app.use('/book', bookRouter);
app.use('/airport', airportRouter);

app.get('/', (req, res) => { // '/'경로에 대한 GET 요청이 발생하면, 콜백 함수가 실행됩니다. 
  res.status(200).send('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;

bookRouter.js

router.get('/', findAll); //첫 번째 인자로는 요청 경로를, 두 번째 인자로는 요청에 대한 콜백 함수를 전달합니다.

router.get('/:phone', findByPhone);

router.get('/:phone/:flight_uuid', findByPhoneAndFlightId);

router.post('/', create);

//Optional
router.delete('/:booking_uuid', deleteByBookingId);

module.exports = router;

flightController.js

const flights = require('../repository/flightList');
const fs = require('fs'); //fs모듈 ex(readFile() ,writeFile() 메소드 사용가능)
module.exports = {
  // [GET] /flight
  // 요청 된 departure_times, arrival_times, destination, departure 값과 동일한 값을 가진 항공편 데이터를 조회합니다.
  findAll: (req, res) => {
    const { departure_times, arrival_times, destination, departure } =
      req.query; //query는 데이터 베이스를 요청한다.
    if (Object.keys(req.query).length === 0) return res.json(flights);
    else if (departure_times !== undefined && arrival_times !== undefined) {
      const data = flights.filter(
        flight =>
          flight.departure_times === departure_times &&
          flight.arrival_times === arrival_times
      );
      return res.json(data); //flights 배열에서 해당 조건을 만족하는 데이터를 필터링하여 data 변수에 할당하고, data를 응답으로 보냅니다.
    } else if (departure !== undefined && destination !== undefined) {
      const data = flights.filter(
        flight =>
          flight.departure === departure && flight.destination === destination
      );
      return res.json(data);
    } else {
      return res.json('Incorrect request');
    }
  },
  // [GET] /flight/:uuid
  // 요청 된 uuid 값과 동일한 uuid 값을 가진 항공편 데이터를 조회합니다.
  findById: (req, res) => {
    // TODO:
    const { uuid } = req.params; //req.params 객체를 사용하여 URL에 포함된 파라미터 값을 가져옵니다. 위 코드에서는 uuid 값을 가져옵니다.
    const data = flights.filter(flight => flight.uuid === uuid);
    return res.json(data);
  },

  // [PUT] /flight/:uuid 요청을 수행합니다.
  // 요청 된 id 값과 동일한 uuid 값을 가진 항공편 데이터를 요쳥 된 Body 데이터로 수정합니다.
  update: (req, res) => {
    const { uuid } = req.params; 
    const bodyData = req.body;
    const beUpdatedIdx = flights.findIndex(flight => flight.uuid === uuid);
    const updatedFlight = { ...flights[beUpdatedIdx], ...bodyData }; //최종적으로 업데이트된 flight
    flights.splice(beUpdatedIdx, 1, updatedFlight);

    /* 파일 수정 */
    // const jsonData = JSON.stringify(flights);
    // fs.writeFileSync(
    //   `${__dirname}/../repository/flightList.js`,
    //   `module.exports = ${jsonData}`
    // );

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

bookController.js

const { v4: uuid } = require('uuid'); //v4는 안전성 보장을 위한 랜덤한 값을 줌. 
// 항공편 예약 데이터를 저장합니다.
let booking = [];

module.exports = {
  // [GET] /book 요청을 수행합니다.
  // 전체 예약 데이터를 조회합니다.
  findAll: (req, res) => {
    return res.status(200).json(booking);
  }
  ,
  // [GET] /book/:phone 요청을 수행합니다.
  // 요청 된 phone과 동일한 phone 예약 데이터를 조회합니다.
  findByPhone: (req, res) => {
    const {phone} = req.params; //HTTP GET 요청의 경로(path)에서 phone 값이 매개변수로 전달됩니다. 이 값을 req.params 객체에서 가져와 phone 변수에 할당합니다.
    const data = booking.filter(book => book.phone === phone);
    return res.status(200).json(data);
  },

  // [GET] /book/:phone/:flight_uuid 요청을 수행합니다.
  // 요청 된 id, phone과 동일한 uuid, phone 예약 데이터를 조회합니다.
  findByPhoneAndFlightId: (req,res) => {
    const {phone, flight_uuid} = req.params;
      const data = booking.filter(book => book.phone === phone && book.flight_uuid === flight_uuid);
      return res.status(200).json(data);
  },
  
  // [POST] /book 요청을 수행합니다.
  // 요청 된 예약 데이터를 저장합니다.
  create: (req, res) => {
    const booking_uuid = uuid();
    const { flight_uuid, name, phone } = req.body;
    if(booking.find(book => book.phone === phone && book.flight_uuid === flight_uuid )){
      return res.status(409).json("It's Already booked.")
    }
    else{
      booking.unshift({booking_uuid, flight_uuid, name, phone});
      res.location(`/book/${booking_uuid}`);
      return res.status(201).json(booking[0])
    }
  },

  // Optional
  // [DELETE] /book/:booking_uuid 요청을 수행합니다.
  // 요청 된 id, phone 값과 동일한 예약 데이터를 삭제합니다.
  deleteByBookingId: (req, res) => {
    const {booking_uuid} = req.params;
    booking = booking.filter(book => book.booking_uuid !== booking_uuid);
    return res.status(200).json({booking_uuid});
  }
};
profile
매일 뭐든하기

0개의 댓글