inflearn logo
강의

講義

知識共有

Node.jsにTypeScriptを適用する(feat. NodeBird)

アンビエントモジュール

Sequelize에 요청을 보내면 오류가 뜹니다

794

Chang Su Lee

投稿した質問数 4

0

수업 보면서 포트폴리오를 작성하고 있습니다...

Sequelize를 통해서 DB에 POST요청을 보내면

TypeError: Class constructor Model cannot be invoked without 'new'

라는 오류가 발생합니다.

Typescript의 버전이 ES6가 아닐 때 시퀼라이즈에서 이러한 오류가 발생한다고 해서 tsconfig에 'target' = 'ES6' 로 지정하니 그때부터 강의를 기반으로 만들어온 모듈 import가 전부 어긋나게 됩니다...

메인페이지의 import * as ... 구문은 어떻게든 수정하겠는데 현재 강의 방식이 아닌 Typescript DB작성 방식을 모르기 때문에 어디서부터 손을 대야 할지도 모르겠습니다

ES6모듈로 전환하지 않고 해당 오류를 해결할 방법이 있을까요? 아니면 ORM을 아예 바꿔야 할까요?

 

nodejs typescript 웹앱

回答 1

0

zerocho

모델 코드를 어떻게 작성하셨나요? 강좌가 오래돼서 옛날 코드일 가능성이 높습니다.

0

Chang Su Lee

index

import User, { associate as associateUser } from "./user";
import Bookmark, { associate as associateBookmark } from "./bookmark";
import Comment, { associate as associateComment } from "./comment";
import Hashtag, { associate as associateHashtag } from "./hashtag";
import Image, { associate as associateImage } from "./image";
import Post, { associate as associatePost } from "./post";
import Schedule, { associate as associateSchedule } from "./schedule";

/* Export */
export * from "./sequelize";

/* Relationship */
const db = {
  Bookmark,
  Comment,
  Hashtag,
  Image,
  Post,
  Schedule,
  User,
};

export type dbType = typeof db;

associateBookmark(db);
associateComment(db);
associateHashtag(db);
associateImage(db);
associatePost(db);
associateSchedule(db);
associateUser(db);

 

sequelize.ts

 

import { Sequelize } from "sequelize";
import config from "../config/config";

/* Env type annotation */
const env =
  (process.env.NODE_ENV as "production" | "test" | "development") ||
  "development";

/* DB connect information */
const { database, username, password } = config[env];
const sequelize = new Sequelize(database, username, password, config[env]);

export { sequelize };
export default sequelize;

 

user.ts

import { Model, DataTypes } from "sequelize";
import { dbType } from "./index";
import { sequelize } from "./sequelize";
import Bookmark from "./bookmark";
import Schedule from "./schedule";
import Post from "./post";

class User extends Model {
  /* User */
  public readonly id!: number;
  public email!: string;
  public password!: string;
  public nickname!: string;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;

  /* Relationship */
  public readonly Bookmarks?: Bookmark[];
  public readonly Schedules?: Schedule[];
  public readonly Posts?: Post[];
  public readonly Followers?: User[];
  public readonly Followings?: User[];

  /* GET SET Methods */
}

User.init(
  {
    email: {
      type: DataTypes.STRING(20),
      allowNull: false,
      unique: true,
    },
    password: {
      type: DataTypes.STRING(100),
      allowNull: false,
    },
    nickname: {
      type: DataTypes.STRING(20),
      allowNull: true,
    },
  },
  {
    sequelize,
    modelName: "User",
    tableName: "user",
    charset: "utf8",
    collate: "utf8_general_ci",
  }
);

export const associate = (db: dbType) => {
  db.User.hasMany(db.Bookmark, { foreignKey: "Users", sourceKey: "id" });
  db.User.hasMany(db.Schedule, { foreignKey: "Users", sourceKey: "id" });
  db.User.hasMany(db.Post, { foreignKey: "Users", sourceKey: "id" });
  db.User.belongsToMany(db.User, {
    through: "Follow",
    as: "Follower",
    foreignKey: "followingId",
  });
  db.User.belongsToMany(db.User, {
    through: "Follow",
    as: "Followings",
    foreignKey: "followerId",
  });
};

export default User;

입니다

 

[0] { email: '', password: '', confirmPassword: '', nickname: '' }

[0] Executing (default): SELECT id, email, password, nickname, createdAt, updatedAt FROM user AS User WHERE User.`email` = '';

[0] TypeError: Class constructor Model cannot be invoked without 'new'

[0] at new User (C:\workspace\Dev-Mark\server\models\user.js:24:42)

[0] at Function.build (C:\workspace\Dev-Mark\server\node_modules\sequelize\lib\model.js:2167:12)

[0] at Function.create (C:\workspace\Dev-Mark\server\node_modules\sequelize\lib\model.js:2220:17)

[0] at C:\workspace\Dev-Mark\server\routes\auth.js:82:56

[0] at step (C:\workspace\Dev-Mark\server\routes\auth.js:44:23)

[0] at Object.next (C:\workspace\Dev-Mark\server\routes\auth.js:25:53)

[0] at fulfilled (C:\workspace\Dev-Mark\server\routes\auth.js:16:58)

[0] POST /auth 500 246.600 ms - 816

[0] TypeError: Class constructor Model cannot be invoked without 'new'

[0] at new User (C:\workspace\Dev-Mark\server\models\user.js:24:42)

[0] at Function.build (C:\workspace\Dev-Mark\server\node_modules\sequelize\lib\model.js:2167:12)

[0] at Function.create (C:\workspace\Dev-Mark\server\node_modules\sequelize\lib\model.js:2220:17)

[0] at C:\workspace\Dev-Mark\server\routes\auth.js:82:56

[0] at step (C:\workspace\Dev-Mark\server\routes\auth.js:44:23)

[0] at Object.next (C:\workspace\Dev-Mark\server\routes\auth.js:25:53)

[0] at fulfilled (C:\workspace\Dev-Mark\server\routes\auth.js:16:58)

0

zerocho

요즘은 시퀄라이즈 타입스크립트 코드를 다음과 같은 식으로 작성합니다.

https://github.com/ZeroCho/nodejs-book/tree/master/ch17/17.4/nodebird/models

0

Chang Su Lee

늦은 시간에 답변 감사합니다 ㅠ

일단 손대기 힘든 Sequelize와 모델을 지우고 나머지를 전부 ES6 import로 전환했습니다

보내주신 코드 따라서 다시 DB 설계해보고 정 모르겠으면 질문 하겠습니다

감사합니다

'S3' 형식에 'S3Client' 형식의 destroy, middlewareStack, send 속성이 없습니다.ts(2739)

0

505

1

throw new Error(`${this.name}.hasMany called with something that's not a subclass of Sequelize.Model`); 에러 질문

0

342

1

안녕하세요.. connect ECONNREFUSED 127.0.0.1:3306 관련해서 질문드립니다

0

955

1

@types를 dependencies에 넣는 이유?

0

398

1

JS에서 babel 사용시 `import * as` 구문을 안써도되는데, 바벨이 esModuleInterop: true 로 처리해주는 것인가요?

0

318

1

Sequelize Association 오류

0

501

2

Sequelize constructor.primaryKeyAttributes 오류

0

960

1

강좌에서 사용된 3개의 코드 의미가 궁금합니다 [ 코드 : 1. [ key:string]:string] 2. delete user.password , 3.passport.deserializeUser<number> ]

0

337

1

@mui/x-data-grid 에 사용자정의 컬럼 타입을 추가해서 사용하려고 합니다.

0

2610

1

미들웨어 에러

1

312

1

Could not find a declaration file for mould '../utils/jwt-utils'

1

180

1

마지막에 type과 interface 추가하는 부분

0

217

1

다른 컴퓨터에서 제가 만든 DB 테이블의 데이터를 그대로 사용하려면?

0

282

1

express 모듈 에러 관련

0

236

1

import * as A from 'B'

0

212

1

MySql ssl 보안 옵션 질문 입니다.

0

351

2

passport/index.ts 에러 입니다

1

450

1

routes/post.ts 페이지에서 에러나요..

0

313

1

passport/index.ts 에러납니다...

0

816

1

ts import 에러

0

440

1

타입스크립트로 변환후 nextjs 빌드 후 배포

0

259

1

sequelize include 질문드립니다.!

0

187

1

roperty 'id' does not exist on type 'User'.

0

894

1

passport user.id 질문드립니다.

0

200

1