코딩테스트 코드 리뷰(?)

Jeongwon Seo·2022년 3월 4일
0

코드리뷰

목록 보기
1/1

이것을 작성해두는 이유는 앞으로 백엔드 MVC 모델을 사용할 때 참고하라고 작성해두는 것임.
최초 작성한 다음에 제출한 다음에 제출한 코드를 작성자가 다시 리뷰해보는 것도 의미가 있으리라.
분명 작성할 때에는 보이지 않던 것이 나중에는 보일 수도 있기에...

코드 구성 과정 개요

  • 앞서 블로그에 게시한 대로 MVC 모델을 사용함.
  • 서버를 구성
  • mysql 설정
  • 콘트롤러 구성
  • 모델 구성

서버 구성 과정(index.js)

  • 서버는 기본적으로 Node.js를 사용하였다.
  • 하지만 바닐라 노드를 쓰면 코드가 복잡할 수 있기에 express.js 미들웨어를 사용하기로 하였다.
  • 라우팅에 대한 설정은 routes 폴더에서 설정하였다.
  • express에서 cors 설정을 위하여 cors 미들웨어를 사용하였다.
  • express 미들웨어를 적용시킬 때 express()를 일일이 쓸 수 없으니 express()를 app이라는 변수를 선언한 다음에 썼다.
  • port는 임의의 숫자로 할당해 주었다.
  • cors 설정은 따로 해주지는 않았다.
  • app.use(express.urlencoded({ extended: true }));은 body-parser 모듈을 사용한 것이다. 요청한 자료의 body부분을 쉽게 추출할수 있게 해주는데, 안의 extended를 true를 쓴다면 JSON 데이터 전송시 중첩된 객체를 허용한다는 뜻이다.
  • 하지만 json 요청을 제대로 받기 위해서는 express.json()을 써줘야 된다.
  • routes 폴더의 index.js는 API 주소를 '/'로 설정한다.
  • 마지막으로 index.js 실행 시 지정된 포트로 실행하게 한다.
const express = require('express');
const indexRouter = require('./routes');
const cors = require('cors');

const app = express();
const port = 9737;
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use('/', indexRouter);

module.exports = app.listen(port, () => {
  console.log(`Server is starting on ${port}`);
});

서버 구성 과정(routes/index.js, items.js)

  • 미리 설정해둔 API 문서에 따라서 라우팅을 구성해준다.
  • API 구성시 parameter를 쓰기 위하여 :id 이런식으로 썼다.
  • get 요청에서 디테일 불러오기를 제외한 부분은 혹시 한번에 쓸 수 있는 코드가 있을지 고민해봐야 겠다.
// index.js
const express = require('express')
const router = express.Router()
const itemsRouter = require('./items')

router.use('/items', itemsRouter)

module.exports = router

// items.js
const router = require('express').Router();
const controller = require('./../controllers');

router.post('/', controller.items.post);
router.get('/:id', controller.items.get);
router.get('/', controller.items.get_all);
router.get('/:id/detailed', controller.items.get_detailed);
router.put('/:id', controller.items.put);
router.put('/:id/detailed', controller.items.put_detailed);
router.delete('/:id', controller.items.delete);

module.exports = router;

sql 설정

  • 서버와 db를 연결, 즉, Node.js와 sql을 연결하는 모듈로 mysql을 설치한다.
  • mysql 설정은 config 파일에 객체로 할당해주었다.
  • 아래에 config는 하나의 객체로 넣는 것이 어땠을 까 하는 생각이 든다.
  • 여기서 아쉬운 점은 password는 환경변수를 사용하는데 github에는 .env.example로 공유를 했어야 되지 않아 싶다.
  • mysql.createConnection(config.development)로 연결을 해준다.
// config/config.js
const dotenv = require('dotenv');
dotenv.config();

const config = {
  development: {
    host: 'localhost',
    user: 'root',
    password: process.env.DATABASE_PASSWORD,
    database: 'bejewel',
  },
};

module.exports = config;

// database/index.js
const mysql = require('mysql');

const config = require('../config/config');

const con = mysql.createConnection(config.development);

con.connect((err) => {
  if (err) throw err;
});

module.exports = con;
  • 보통 id값은 AUTO_INCREMENT로 지정을 해두나, id값을 직접 지정할 경우에는 그냥 id INT로 써야 된다.
  • 입력값이 고정된 글자수가 아니기 때문에 VARCHAR를 사용하였다.
  • 아래의 PRIMARY KEY는 반드시 지정해두어야한다.(아래 한줄 때문에 에러가...)
  • 사실 등록시에 디테일 페이지까지 다 썼는데 이것을 따로 저장할 방법은 없는지 고민해봐야겠다.
// schema.sql
CREATE TABLE items (
    id INT,
    name varchar(255),
    description varchar(255),
    price INT,
    inventory INT,
    image varchar(255),
    category varchar(255),
    material_base varchar(80),
    material_etc varchar(80),
    material_plated varchar(80),
    material_stone varchar(80),
    shape varchar(80),
    size varchar(80),
    weight varchar(80),
    PRIMARY KEY (id)

)
profile
피트는 구덩이라는 뜻이다 구덩이를 파다보면 좋은 것이 나오겠지 (아싸 벡스룬)

0개의 댓글