저장을 습관화

230725 TIL - 데이터 타입 enum, babel 본문

공부/TIL

230725 TIL - 데이터 타입 enum, babel

ctrs 2023. 7. 26. 00:12

- 데이터 타입 enum

enum이란 특정 값들 중 하나를 선택할 수 있는 타입임

회원가입할때 성별이나 태어난 년도 선택하는 셀렉트 박스를 만들때 쓰임

 

npx seuqelize model:generate 명령문 이용해서 테이블 만들때

데이터 타입 enum 사용하는 방법

대부분의 다른 타입들처럼 컬럼명:타입명 이 아니라

'컬럼명:enum:{option1,option2,option3}' 이렇게 해줘야함

 

예시)

npx sequelize model:generate --name item --attributes name:string,option_id:integer,price:integer,'type:enum:{coffee,juice,food}',amount:integer

위 명령어를 입력하면

migrations와 models 폴더에 파일이 생성됨

 

/migrations/20230725041100-create-item.js

'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('items', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      name: {
        type: Sequelize.STRING
      },
      option_id: {
        type: Sequelize.INTEGER
      },
      price: {
        type: Sequelize.INTEGER
      },
      type: {
        type: Sequelize.ENUM('coffee', 'juice', 'food')
      },
      amount: {
        type: Sequelize.INTEGER
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  async down(queryInterface, Sequelize) {
    await queryInterface.dropTable('items');
  }
};

 

/models/item.js

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class item extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  }
  item.init({
    name: DataTypes.STRING,
    option_id: DataTypes.INTEGER,
    price: DataTypes.INTEGER,
    type: DataTypes.ENUM('coffee', 'juice', 'food'),
    amount: DataTypes.INTEGER
  }, {
    sequelize,
    modelName: 'item',
  });
  return item;
};

 

그럼 이제 이걸 상황에 맞춰 수정한 후 사용하면 됨

 

 

[출처] 구글링

https://www.appsloveworld.com/sequelizejs/100/2/not-able-to-create-enum-type-attribute-using-sequelize-cli

 

[Solved]-Not able to create ENUM type attribute using sequelize cli-sequelize.js

Coding example for the question Not able to create ENUM type attribute using sequelize cli-sequelize.js

www.appsloveworld.com

 

 

- babel 바벨

자바스크립트로 코드를 작성할 때,

최신 버전의 문법을 사용하여 작성하였다면

 

이를 실행할 브라우저에 따라 해당 버전의 문법을 지원하지 않을 수도 있음

이 경우 정상적으로 작성한 코드여도 SyntaxError, 문법 오류가 발생함

 

하지만 모든 브라우저에서 실행이 가능하게끔 코드를 작성하려면

ES5 이하의 방식으로 코드를 작성해야하는데.. 이건 싫음

 

이럴 때 사용하는 것이 babel 바벨임

자바스크립트 컴파일러라고 생각하면 됨

 

예시)

1. test.js 파일 생성

ES6부터 사용가능한 화살표 함수가 쓰여있다.

// test.js
[1, 2, 3].map((n) => n + 1);

 

2. babel 패키지 설치

@babel/core가 바벨을 사용하기 위한 필수 패키지이며,

@babel/cli가 바벨 명령어를 입력하기 위한 패지키이다.

개발중에만 쓰일 것이기 때문에 -D 옵션을 넣어준다.

$ npm init -y
$ npm install -D @babel/core @babel/cli

 

3. 프리셋 설정

가장 많이 사용되는 env preset를 사용한다.

env preset은 ES6 이상의 문법을 ES5 문법으로 바꾸도록 되어있다.

$ npm install -D @babel/preset-env

설치 후 터미널에 babel 명령어와 문법을 수정할 파일명, 프리셋을 입력하면

ES5 문법으로 변경된 코드를 출력한다.

$ npx babel test.js --presets=@babel/env
"use strict";

[1, 2, 3].map(function (n) {
  return n + 1;
});

 

4. babel 설정 파일

매번 바벨을 사용할때마다 프리셋 옵션을 넣기 귀찮으니 설정 파일을 만든다.

파일명은 .babelrc 혹은 babel.config.js로 한다. 확장자가 js여도 아이콘이 바벨 아이콘이다.

babel 7 버전부터는 .babelrc 파일보다 babel.config.js를 사용하는 것을 권장된다고 한다.

.babelrc는 파일이 위치한 디렉토리에 존재하는 파일에만 적용이 가능해서

모든 폴더에 만들거나 사용시 파일의 경로를 지정해줘야했다

 

babel.config.js는 파일이 루트 디렉토리에 위치하면 프로젝트 전체에 사용이 가능하다.

 

.babelrc는 JSON형식이나 babel.config.js는 자바스크립트 형식이라 설정하기도 편하다.

 

.babelrc

{
  "presets": ["@babel/env"]
}
$ npx babel test.js
"use strict";

[1, 2, 3].map(function (n) {
  return n + 1;
});

or

 

babel.config.js

module.exports = {
  presets: ["@babel/env"],
};
$ npx babel test.js
"use strict";

[1, 2, 3].map(function (n) {
  return n + 1;
});

 

하나의 디렉토리에 .babelrc와 babel.config.js를 같이 두지 않도록하자

바벨이 .babelrc 파일을 우선으로 확인해서 해당 파일의 내용이 없다면 에러를 출력한다.

 

 

5. 출력 내용을 다른 이름의 파일로 생성

문법 
$ npx babel (원본 파일) -o (신규 파일)

예시)

$ npx babel test.js -o new.js

new.js 파일 생성 확인

"use strict";

[1, 2, 3].map(function (n) {
  return n + 1;
});

 

자바스크립트 뿐 아니라 타입스크립트와 JSX에도 사용가능하다고 하니 잘 기억해두자

 

근데 처음엔 몰랐는데 적다가 다시보니 이름이 구약 성경에 나오는 바벨탑의 바벨이네

이름 잘지었다 바벨탑이 중단된 이유도 건설자들끼리 언어가 통하지 않아서 였으니까..

재밌네

 

[출처]

https://www.daleseo.com/js-babel/

 

바벨(Babel 7) 기본 사용법

Engineering Blog by Dale Seo

www.daleseo.com

 

'공부 > TIL' 카테고리의 다른 글

230807 TIL - 데이터 타입 변환, Number()와 parseInt()의 차이, .toString()과 +""  (0) 2023.08.07
230801 TIL - TypeScript 강의 요약 및 추가 학습 자료  (0) 2023.08.02
230710 TIL  (0) 2023.07.10
230706 TIL  (0) 2023.07.06
230704 TIL  (0) 2023.07.04