모도리는 공부중

[TypeScript, NestJS] No metadata for * was found 본문

내 지식 정리/JAVASCRIPT

[TypeScript, NestJS] No metadata for * was found

공부하는 모도리 2023. 3. 16. 14:53
728x90
반응형

문체가 반말인 점, 미리 양해 부탁드립니다.

친구에게 하소연, 일기장, 독백처럼 말하고 있다고 생각하고 정겹게 읽어주세요.

 

ERROR [ExceptionsHandler] No metadata for "User" was found.
EntityMetadataNotFoundError: No metadata for "User" was found.

 

NestJS 오픈된 강의를 들으면서 Board 생성을 진행하던 중, typeorm 버전 문제로 이미 여러 차례 고생을 하고 있었다.

가장 빠른 방법은 다운그레이드 후 하는 것이었지만 그렇게 하기는 왠지 모르게 싫더라. 그래서 여러 사람들의 쌩고생 후일담을 보며 겨우겨우 해결을 했었다. 내가 참고했던 링크들이 아래(더보기)와 같다.

더보기

 

User도 같은 방식으로 진행하면 되겠지? 하면서 수정을 했는데, 아무리 해도 계속 진행이 안되는 거다. 왜?? 대체 왜?? 하면서 보니까 맨 마지막 방식을 잊어서였더라고.

근데 여기서 의문이 튀어나오고 답답해졌다. 아니, 쉽게 편하게 하려고 entities를 경로 방식에 *까지 집어넣어 지정해놨는데 왜 굳이 내가 필요한 Board와 User를 따로 import해줘야 해? 이게 더 문제 아닌가? 이런식으로 하면 계속 추가추가만 해서 번잡스러워질텐데?

그래서 도무지 못 참겠다, 하며 '__dirname'의 정체를 뜯어보기로 했다.

import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { User } from 'src/auth/user.entity';
import { Board } from 'src/boards/board.entity';

export const typeORMConfig: TypeOrmModuleOptions = {
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'postgres',
  password: '비밀입니다만?',
  database: 'board-app',
  entities: [
    `${console.log('entities dirname', __dirname)}`,
    __dirname + '/../**/*.entity.ts',
  ],
  synchronize: true,
};

기존의 [ __dirname + '/../**/*.entity.{js,ts}' ]를 놓고 봤을 때, dirname은 현재 config가 위치한 경로일 것으로 추정된다.

내 디렉토리는 이렇게 생겼거든.

└inflearnboardapp
  ├dist
  ├node_modules
  └src
    ├auth
    ├boards
    └configs

이렇게 해서 콘솔을 찍어보니..

entities dirname C:\Users\modory\뭐가많네요\inflearnBoardApp\dist\configs

아? 아아??

노마드 코더의 TypeScript 오픈된 강의 들을 때 TS로 작성한 코드는 JS로 변환을 해줘야 해서 항상 npm run build를 진행해주어야만 했다. 그 과정이 NestJS 공부하면서 안 나오고 npm run start:dev로 해결되길래 안 그래도 궁금했었는데, build 폴더에 저장될 내용이 dist에 변환돼서 저장되고 있었던 것이다.

└inflearnboardapp
  ├dist
    ├auth
    ├boards
    └configs
  ├node_modules
  └src
    ├auth
    ├boards
    └configs

다시 말하면, src에 작성한 코드가 아니라 dist로 변환된 코드가 실행되고 있기에 configs에서 말하는 __dirname이 저렇게 나오게 된다.

 

어떻게 변환되는지 본격적으로 뜯어보자.

기본

src/configs/typeorm.config.ts

import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { User } from 'src/auth/user.entity';
import { Board } from 'src/boards/board.entity';

export const typeORMConfig: TypeOrmModuleOptions = {
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'postgres',
  password: '비밀',
  database: 'board-app',
  entities: [__dirname + '/../**/*.entity.{js,ts}'],
  synchronize: true,
};

dist/configs/typeorm.config.js

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.typeORMConfig = void 0;
exports.typeORMConfig = {
    type: 'postgres',
    host: 'localhost',
    port: 5432,
    username: 'postgres',
    password: '비밀',
    database: 'board-app',
    entities: [__dirname + '/../**/*.entity.{js,ts}'],
    synchronize: true,
};
//# sourceMappingURL=typeorm.config.js.map

각 엔티티 직접 추가한 형태

src/configs/typeorm.config.ts

import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { User } from 'src/auth/user.entity';
import { Board } from 'src/boards/board.entity';

export const typeORMConfig: TypeOrmModuleOptions = {
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'postgres',
  password: '비밀',
  database: 'board-app',
  entities: [__dirname + '/../**/*.entity.{js,ts}', Board, User],
  synchronize: true,
};

dist/configs/typeorm.config.js

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.typeORMConfig = void 0;
const user_entity_1 = require("../auth/user.entity");
const board_entity_1 = require("../boards/board.entity");
exports.typeORMConfig = {
    type: 'postgres',
    host: 'localhost',
    port: 5432,
    username: 'postgres',
    password: '비밀',
    database: 'board-app',
    entities: [__dirname + '/../**/*.entity.{js,ts}', board_entity_1.Board, user_entity_1.User],
    synchronize: true,
};
//# sourceMappingURL=typeorm.config.js.map

.... 답답 터진다. 아무리 봐도 다른 해결 방법이 있어야 정상이라는 생각이 든다. 그래서 github에 작성된 수많은 답변을 찾아 헤맸다.

https://github.com/typeorm/typeorm/issues/1327#issuecomment-1370307247

 

{ EntityMetadataNotFound: No metadata for "User" was found. · Issue #1327 · typeorm/typeorm

Hello, I'm trying to setup a new project using the latest release and the ormconfig.yml options. I'm following the documentation and pointing it to the src/entity/*.js location, but i keep ...

github.com

드디어... 내가 원하는 답을 찾아냈다. 우선은 저 사람처럼 entities 수정을 진행했다.

import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { User } from 'src/auth/user.entity';
import { Board } from 'src/boards/board.entity';

export const typeORMConfig: TypeOrmModuleOptions = {
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'postgres',
  password: '비밀',
  database: 'board-app',
  entities: [
    'src/**/*.entity.{js,ts}',
    'dist/**/*.entity.{js,ts}'
  ],
  synchronize: true
};

안 된다. 답변을 다시 보니 처음 보는 autoLoadEntities가 보인다. 이 녀석이 답일 것 같다. 설명을 번역해보자.

그래? 그럼 true 넣어줄게.

src/configs/typeorm.config.ts

import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { User } from 'src/auth/user.entity';
import { Board } from 'src/boards/board.entity';

export const typeORMConfig: TypeOrmModuleOptions = {
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'postgres',
  password: '비밀',
  database: 'board-app',
  entities: [
    __dirname + '/../**/*.entity.{js,ts}',
    // 'src/**/*.entity.{js,ts}',
    // 'dist/**/*.entity.{js,ts}'
  ],
  synchronize: true,
  autoLoadEntities: true,
};

그리고 다시 postman 테스트!

된다!!!!!!!!!!!!!!!!!!!!

 

주석처리해놓은 거 지우고 다시 정리하면 되겠다. 햐, 마음이 편해졌다.

728x90
반응형
Comments