IT/프로그래밍

좌충우돌 Sequelize 5.x 에서 Sequelize 6.x 로 마이그레이션

홀롤록 2021. 3. 31. 14:47
반응형

회사에서 Sequelize 5.x -> Sequelize 6.x 로 마이그레이션을 해보려던 중 마주쳤던 라이브러리 지원 함수 삭제 등으로 인한 이슈가 있었다.

오늘은 이에 대해 한 번 써보려한다. 
회사에서 5.x -> 6.x 을 진행하면서 생겼던 내용에 대해서만 기술하기 때문에, 이외에 다른 내용이 있다면 댓글로 작성해주시거나 하면 다른 분들에게도 공유될 수 있어 좋을 것 같습니다 ^오^

 

우선적으로 회사에선 기존에 Sequelize 4.x 와 Sequelize 5.x 를 각 프로젝트에서 쓰고 있었다. 하지만 지금의 Sequelize 버전은 몇이지..?!
무려 6버전이다.. 자잘한 Minor 버전을 제외한다고 해도 라이브러리 버전이 차이가 난다. 그리고 NodeJS 버전도 낮았기에.. 하하..

 

라이브러리 버전을 바꿔서 프로젝트 구성을 하고 기존에 사용하던 방식인, 스키마를 선언하고, 선언한 스키마의 파일 위치를 찾아 require 해주는 방식을 사용해보았다.

// 스키마 선언
module.exports = (sequelize, DataTypes) => {
	const Model = sequelize.define(
    'testBlog',
    {
    	title: {
		type: DataTypes.STRING(10),
            allowNull: false,
            primaryKey: true,
        },
        likeCount: {
        	type: DataTypes.INTEGER(5).UNSIGNED
            allowNull: false,
            defaultValue: 0,
        }
    }
};
// Sequelize 4.x
fs.readdirSync(__dirname).forEach((file) => {
  if (path.extname(file) === '.js' && file !== baseName) {
    const filePath = path.join(__dirname, file);
    const r = require(filePath); // eslint-disable-line global-require

    if (r) {
      const model = sequelize.import(filePath, r);
      db[model.name] = model;
    }
  }
});

// Sequelize 5.x
fs.readdirSync(__dirname).forEach((model) => {
  if (['index.js', '_migrations'].indexOf(model) !== -1) return;
  const modelFilePath = path.join(__dirname, model, 'index.js');
  if (fs.existsSync(modelFilePath) && fs.lstatSync(modelFilePath).isFile()) {
    model = sequelize.import(modelFilePath);
    db[model.name] = model;
  }
});

 

 

기존에 위 처럼 사용했었는데, 기존 5버전에서 6 버전으로 똑같이 하게 되면, 

TypeError: sequelize.import is not a function

위와 같은 에러가 발생하게 된다. 이 에러는 Sequelize 공식 홈페이지에서 확인할 수 있는데 문서상에 작성된 내용은 다음과 같다.

Deprecated: sequelize.import

Note: You should not use sequelize.import. Please just use require instead.

This documentation has been kept just in case you really need to maintain old code that uses it.

You can store your model definitions in a single file using the sequelize.import method. The returned object is exactly the same as defined in the imported file's function. The import is cached, just like require, so you won't run into trouble if importing a file more than once.

영어를 잘하진 못하지만 가볍게 보면 Defrecated 되었다고 나오고, requre를 사용하라고 본문 아래에선 가이드를 해주고 있다.
그 내용을 따라 위 5.x 에서 사용한 내용을 수정해보면, 

fs.readdirSync(__dirname).forEach((model) => {
  if (['index.js', '_migrations'].indexOf(model) !== -1) return;
  const modelFilePath = path.join(__dirname, model, 'index.js');
  if (fs.existsSync(modelFilePath) && fs.lstatSync(modelFilePath).isFile()) {
    model = require(modelFilePath)(sequelize, DataTypes);
    db[model.name] = model;
  }
});

이렇게 수정할 수 있고, 수정된 내용이 정상적으로 동작하여 Sequelize 를 사용할 수 있게 됐다.

 

 

반응형