깊은바다거북
개발 공부 기록
깊은바다거북
전체 방문자
오늘
어제
  • 분류 전체보기 (219)
    • JAVA (9)
    • JavaScript (15)
    • 스파르타코딩클럽 (11)
      • [내일배움단] 웹개발 종합반 개발일지 (5)
      • [내일배움캠프] 프로젝트와 트러블 슈팅 (6)
    • SQL | NoSQL (4)
    • CS 등등 (0)
    • TIL | WIL (173)
    • 기타 에러 해결 (3)
    • 내 살 길 궁리 (4)

인기 글

최근 글

최근 댓글

태그

  • Backtracking(백트래킹)
  • leetcode-cli
  • 최소 힙(Min Heap)
  • 혼자 공부하는 자바스크립트
  • Linked List
  • POST / GET 요청
  • Binary Tree(이진 트리)
  • Trie
  • Inorder Traversal(중위 순회)
  • 프로그래머스
  • BST(이진 탐색 트리)
  • BFS(너비우선탐색)
  • Preorder Traversal(전위 순회)
  • 재귀 함수
  • 트러블 슈팅 Troubleshooting
  • 팀 프로젝트
  • tree
  • 코딩테스트 연습문제
  • 자잘한 에러 해결
  • 01. 미니 프로젝트
  • 최대 힙(Max Heap)
  • Leetcode
  • 자료 구조
  • DFS(깊이우선탐색)
  • 자바스크립트 기초 문법
  • TIT (Today I Troubleshot)
  • Til
  • TypeScript
  • 시간 복잡도
  • 점화식(Recurrence Relation)
hELLO · Designed By 정상우.
깊은바다거북

개발 공부 기록

TIL | WIL

3/12 일 (req.user 정보를 불러오지 못할 땐 app.module 확인하기) TIL, TIT

2023. 4. 6. 20:03

(최종 프로젝트 진행중)

한 일:

  • queryBuilder 문서 보던중. 두 번 조인과 그 때 select하는 법, (https://typeorm.io/select-query-builder#join-without-selection)
  • 그렇게 가져온 ‘정재된 결과물’을 partial 타입으로 넘겨서 테스트 할 것인지… 그렇다면 어떻게.. …?
  • 테스트 코드 강의 노트와 유튜브 보던 중

(나중에 볼 만한 것)

  • 로그인 e2e. jwt토큰 검증으로 HttpStatus.FORBIDDEN에서 OK로 만들기
NestJS e2e Testing
In this video we primarily work on a integration test for our authentication controller with Super Test. We also discuss approaching e2e testing for the application. and determine the different ways and circumstances integration and e2e tests are used. Previous video: https://youtu.be/43iQzPJvZDw GitHub: https://github.com/Jon-Peppinck/linkedin-clone Please support the channel: 1. System Design Interview: https://amzn.to/3WeBTOB 2. Cracking the Coding Interview: https://amzn.to/3BvUuxw 3. Introduction to Algorithms - CLRS: https://amzn.to/3FpHZF3 4. The Algorithm Design Manual: https://amzn.to/3FJefmX 5. Design Patterns - Gang of Four: https://amzn.to/3hqYmJp 6. Clean Code - Uncle Bob: https://amzn.to/3PmWU7s 7. Rode NT1 Microphone: https://amzn.to/3Bu7FPy As an Amazon Associate I earn from qualifying purchases. ---------------------------------------------------------------------------- Follow Me On: Facebook: https://web.facebook.com/profile.php?id=100088213423272 Twitter: @jon_peppinck GitHub: https://github.com/Jon-Peppinck Subscribe to My YouTube Channel For More: https://www.youtube.com/@JonPeppinck ---------------------------------------------------------------------------- Watch These Videos As Well: 1: Amazon Clone - React + Redux + NestJS + Mongo https://www.youtube.com/playlist?list=PL9_OU-1M9E_sGc8wmVspxGwHUdCqDV8pM 2: NextJS TypeScript Code Blog: https://www.youtube.com/playlist?list=PL9_OU-1M9E_uVY-FW0GZr7FwqYeOouzKh 3: LinkedIn Clone - Ionic + Angular + NestJS + PostGreSQL: https://www.youtube.com/playlist?list=PL9_OU-1M9E_ut3NA04C4eHZuuAFQOUwT0 4: MEAN: https://www.youtube.com/playlist?list=PL9_OU-1M9E_sKxLuX_bf4_TmYdwCt_nKX 5: React: https://www.youtube.com/playlist?list=PL9_OU-1M9E_tAvRZspBEog2xdeO7XXg_Y 6: Angular Node MySQL - Login System: https://www.youtube.com/playlist?list=PL9_OU-1M9E_sjaUPfH3FIp8GtJrhJhTb8 ------------------------------------------------------------------------
https://www.youtube.com/watch?v=6OPGp_WHJuU
  • Express 방식으로 (req, res, next) 소스 코드와 테스트 코드 쓰기 (도움이 될까..?)
NestJS Testing Tutorial #1 - Unit Testing Controllers
Become a Member: https://www.youtube.com/ansonthedeveloper/join Become a Patreon: http://patreon.com/stuyy Buy me a Coffee: http://ko-fi.com/anson Donate on Streamlabs: https://streamlabs.com/ansondevacademy/tip Donate on PayPal: https://paypal.me/ansonfoong Connect with me: Discord: http://discord.gg/bZSwjPy GitHub: http://github.com/stuyy Twitch: http://twitch.tv/stuy
https://www.youtube.com/watch?app=desktop&v=lih9VT0IZ7U
  • IsCreateorGuard라는.. 게.. 있어서..?! ‘로그인 유저가 작성자인지 검사’
NestJS Unit Testing - Test Controller (with Guards) and Service
In this video we use Jest to create unit tests for our feed controller and service. The feed controller has guards and other dependencies are mocked. We also unit test our service, which has an observable. After watching this video you will understand how to do unit tests with Jest, particularly within a NestJS environment. Previous video: https://youtu.be/dAxO1sfrnjM GitHub: https://github.com/Jon-Peppinck/linkedin-clone Please support the channel: 1. System Design Interview: https://amzn.to/3WeBTOB 2. Cracking the Coding Interview: https://amzn.to/3BvUuxw 3. Introduction to Algorithms - CLRS: https://amzn.to/3FpHZF3 4. The Algorithm Design Manual: https://amzn.to/3FJefmX 5. Design Patterns - Gang of Four: https://amzn.to/3hqYmJp 6. Clean Code - Uncle Bob: https://amzn.to/3PmWU7s 7. Rode NT1 Microphone: https://amzn.to/3Bu7FPy As an Amazon Associate I earn from qualifying purchases. ---------------------------------------------------------------------------- Follow Me On: Facebook: https://web.facebook.com/profile.php?id=100088213423272 Twitter: @jon_peppinck GitHub: https://github.com/Jon-Peppinck Subscribe to My YouTube Channel For More: https://www.youtube.com/@JonPeppinck ---------------------------------------------------------------------------- Watch These Videos As Well: 1: Amazon Clone - React + Redux + NestJS + Mongo https://www.youtube.com/playlist?list=PL9_OU-1M9E_sGc8wmVspxGwHUdCqDV8pM 2: NextJS TypeScript Code Blog: https://www.youtube.com/playlist?list=PL9_OU-1M9E_uVY-FW0GZr7FwqYeOouzKh 3: LinkedIn Clone - Ionic + Angular + NestJS + PostGreSQL: https://www.youtube.com/playlist?list=PL9_OU-1M9E_ut3NA04C4eHZuuAFQOUwT0 4: MEAN: https://www.youtube.com/playlist?list=PL9_OU-1M9E_sKxLuX_bf4_TmYdwCt_nKX 5: React: https://www.youtube.com/playlist?list=PL9_OU-1M9E_tAvRZspBEog2xdeO7XXg_Y 6: Angular Node MySQL - Login System: https://www.youtube.com/playlist?list=PL9_OU-1M9E_sjaUPfH3FIp8GtJrhJhTb8 ------------------------------------------------------------------------
https://www.youtube.com/watch?v=43iQzPJvZDw

  • Nest.js 파일 업로드 테스트하는 방법

무슨 stream으로 Unit Test 코드 만들기 - https://stackoverflow.com/questions/67377812/mock-file-upload-in-unit-test-controller-nestjs

PostMan의 form-data와 ‘select files’버튼(?)’을 이용해 테스트하기 - https://stackoverflow.com/questions/61148959/fileinterceptor-and-body-issue-in-nestjs-upload-a-file-and-data-in-a-request

Nest.js 홈페이지에서 소개하는 터미널 명령어 방법

https://github.com/nestjs/nest/tree/master/sample/29-file-upload

  • [Nest.js] Sample 코드 일체 (auth-jwt, file-upload 등. 별로 혹할 만한 건 없음)
nest/sample at master · nestjs/nest
A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications on top of TypeScript & JavaScript (ES6, ES7, ES8) 🚀 - nest/sample at master ·...
https://github.com/nestjs/nest/tree/master/sample

  • NodeMailer 블로그 포스팅
[NestJS] mail 발송(Gmail,nodeMailer)
설치법 yarn add @nestjs-modules/mailer nodemailer #or npm install --save @nestjs-modules/mailer nodemailer 만약 template을 사용하려면 셋 중에 하나를 다운 받아야 한다. // with npm npm install --save handlebars #or npm install --save pug #or npm install --save ejs // with yarn yarn add handlebars #or yarn add pug #or yarn add ejs 일단 모듈 구현 코드 먼저 보면서 설명을 하겠다. // email.module.ts import { Module } from "@nestjs/common"; impo..
https://coking.tistory.com/19

  • 쪽지 기능 구현하기
쪽지 시스템 구현기
쪽지 구현하기
https://velog.io/@yukina1418/쪽지-시스템-구현기
상호작용 데이터모델링 : NHN Cloud Meetup
상호작용 데이터모델링
https://meetup.nhncloud.com/posts/108


※ 이하는 스스로 공부하며 적어둔 노트이며 불확실한 내용이 있을 수 있습니다. 학습용으로 적합하지 않음을 유념해주세요. ※

[Nest.js] 에러 TypeError: Cannot read properties of undefined (reading 'name') ✔️

발생 상황: pull을 받고 Nest.js 애플리케이션 서버를 실행해보려는데 발생.

에러 메세지 전문:

[오후 4:27:33] Starting compilation in watch mode...

[오후 4:27:42] Found 0 errors. Watching for file changes.

[Nest] 19260  - 2023. 03. 12. 오후 4:27:46     LOG [NestFactory] Starting Nest application...
[Nest] 19260  - 2023. 03. 12. 오후 4:27:46   ERROR [ExceptionHandler] Cannot read properties of undefined (reading 'name')
TypeError: Cannot read properties of undefined (reading 'name')
    at new DataSource (C:\Users\USER\Desktop\Sparta\05_project_무인냥품\src\data-source\DataSource.ts:130:29)
    at Injector.instantiateClass (C:\Users\USER\Desktop\Sparta\05_project_무인냥품\node_modules\@nestjs\core\injector\injector.js:351:19)
    at callback (C:\Users\USER\Desktop\Sparta\05_project_무인냥품\node_modules\@nestjs\core\injector\injector.js:56:45)
    at Injector.resolveConstructorParams (C:\Users\USER\Desktop\Sparta\05_project_무인냥품\node_modules\@nestjs\core\injector\injector.js:136:24)    at Injector.loadInstance (C:\Users\USER\Desktop\Sparta\05_project_무인냥품\node_modules\@nestjs\core\injector\injector.js:61:13)
    at Injector.loadProvider (C:\Users\USER\Desktop\Sparta\05_project_무인냥품\node_modules\@nestjs\core\injector\injector.js:88:9)
    at C:\Users\USER\Desktop\Sparta\05_project_무인냥품\node_modules\@nestjs\core\injector\instance-loader.js:49:13    
    at async Promise.all (index 0)
    at InstanceLoader.createInstancesOfProviders (C:\Users\USER\Desktop\Sparta\05_project_무인냥품\node_modules\@nestjs\core\injector\instance-loader.js:48:9)
    at C:\Users\USER\Desktop\Sparta\05_project_무인냥품\node_modules\@nestjs\core\injector\instance-loader.js:33:13

시도:

이상한 것은 내 프로젝트 폴더의 src폴더 안에는 저 data-source라는 경로가 없다는 것이다… 에러 메세지를 읽어봐도 찾아가서 고쳐볼만한 유효한 경로가 나오지 않고 다 node_module의 코드들이다.

더 이상한 것은 받아온 코드가 깃헙에서 DI 테스트를 (그것도 Node 버전별로) 통과했다는 것이다… 나한테 와서 이상해졌다는 건가?

아무리 찾아봐도 레퍼런스가 안 나왔다.

DataSource로 그냥 파일 검색하고 셀프 추론으로 해결하였다… 허허….

원인:

해결: messages.module.ts에서 imports되는 DataSource를 삭제하였더니 서버가 다시 잘 켜졌다.

// src/messages/messages.module.ts
...
import { DataSource } from 'typeorm';
import { Message } from './message.entity';

@Module({
  imports: [TypeOrmModule.forFeature([Message]), DataSource],
  controllers: [MessagesController],
  providers: [MessagesService, MessagesRepository],
})
export class MessagesModule {}

[Nest.js] req.user를 기어코 인식하지 못할 때 ✔️

messages.controller.ts를 작성하는데, 옆집 requests 모듈의 controller에서와 정확히 똑같이 @Req() req를 임포트해주고 사용하는데도 req.user가 undefined로 떴었다.

이렇게 정말 이상하게 req.user를 도무지 인식하지 못할 때는 app.module에 문제가 있는 것이다.

⇒ app.module에 authMiddleware 경로 설정을 추가해줬는지 체크하기:

// app.module.ts
@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      useClass: TypeOrmConfigService,
      inject: [ConfigService],
    }),
    JwtModule.registerAsync({
      imports: [ConfigModule],
      useClass: JwtConfigService,
      inject: [ConfigService],
    }),
    UsersModule,
		...
  ],
  controllers: [AppController],
  providers: [AppService, AuthMiddleware],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(AuthMiddleware)
      .forRoutes(
        { path: 'auth/logout', method: RequestMethod.ALL },
				{ path: 'messages', method: RequestMethod.POST },
        { path: 'messages/sent', method: RequestMethod.GET },
        { path: 'messages/received', method: RequestMethod.GET },
      );
  }
}

[TypeORM] 두 번 조인과 select 하기 ✔️

async getSentMessages(senderId: number): Promise<Partial<Message>[]> {
  const messages = await this.createQueryBuilder('m')
    .leftJoin('m.send_user', 'sender')
    .leftJoin('m.receive_user', 'receiver')
    .addSelect(['sender.nickname', 'receiver.nickname'])
    .where('m.sender_id = :senderId', { senderId })
    .getMany();
  return messages;
}

⇒ 일단 select()가 하나도 없으면 기본적으로 m (Message)의 모든 컬럼 선택

⇒ 설명 생략. 어쨌든 잘 됨을 확인했다.


Uploaded by N2T

    'TIL | WIL' 카테고리의 다른 글
    • 3/14 화 (ejs는 일일이 눈으로 검사해서 에러를 찾아야 함이 불편) TIL, TIT
    • 3/13 월 (VS Code의 Rest Client 옵션을 초기화해주다) TIL, TIT
    • 3/11 토 (모듈 하나 e2e테스트 성공, Date타입의 toString 종류 총정리) TIL, TIT
    • 3/10 금 (구현할 기술 파트와 범위를 구체적으로 재설정하다) TIL, TIT
    깊은바다거북
    깊은바다거북

    티스토리툴바