묻고 답해요
160만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
해결됨타입스크립트의 모든 것
데코레이터-2 강의 질문이 있습니다.
데코레이터-2 강의에서 팩토리 안에 있는 데코레이터 함수를 실행하면 첫번째 인자인 target: Function쪽에는 강의와 다르게 빈값({})이 출력되는데요..! 혹시 이유를 아실까하여 여쭤봅니다..!tsconfig.json에서 말씀해주신 2개의 옵션 수정한 상태입니다.좋은 강의에 감사의 말씀 전달드립니다!!class HelloController { @Get("/api/v1/user") getRequest() {} } function Get(params: any): any { console.log("Get factory params : ", params); return ( target: any, propertyKey: string, descriptor: PropertyDescriptor) => { console.log("Get deco func : ", target); console.log("Get propertyKey : ", propertyKey); console.log("Get descriptor: ", descriptor); } } 출력값 Get factory params : /api/v1/user Get deco func : {} Get propertyKey : getRequest Get descriptor: { value: [Function: getRequest], writable: true, enumerable: false, configurable: true }
-
해결됨[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
[질문] 토큰 만료에 대한 예외처리 질문
안녕하세요, 현재 강의 를 듣고 있는 수강생입니다.BearerTokenGuard를 작성하고, 토큰 유효기간이 지난 경우에 대해서도테스트 상황을 가정하여 전날 만들어둔 access token을 authorization header에 넣어테스트 해보았습니다. 그런데 verifyToken api에 try,catch문이 없어서 500 코드의 에러가 발생하더라구요.그래서 일단 401 error를 내는게 맞는것 같아서 아래와 같이 작성을 했는데, verify의 결과가 무조건 토큰이만료된 경우 1가지인지 확실치 않아, 잘 작성된 코드인지 모르겠어서 질문 드립니다. 어떻게 예외처리 코드를 작성하면 좋을까요? /* 해당 API는 토큰을 검증하는 API 입니다. */ verifyToken(token: string) { try { const result = this.jwtService.verify(token, { secret: JWT_SECRET, }); return result; } catch (error) { // to-do : 나중에 최적화 throw new UnauthorizedException('만료된 토큰입니다. 재발급해주세요'); } }
-
해결됨타입스크립트의 모든 것
enum 질문이 있습니다.
안녕하세요! 강의 잘 보구 있습니다.enum에는 값 외에 object나 함수를 지정할 수 없나요?java에서의 enum에서는 값 외에 행위나 인터페이스 등의 타입을 부여할 수 있어서 혹시 가능한지 여쭤봅니다 ㅎㅎ
-
해결됨[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
many to many relations update를 할 경우 질문 드립니다.
안녕하세요. 강의 정말 잘 듣고 있습니다.먼저 좋은 강의 감사드립니다.강의를 듣고 복습을 하던 중에, 기존 tag가 relation된 post를 찾아서 새로운 tag를 추가하는 API는 어떤 식으로 짜야 하는지 궁금해서 질문 드립니다.
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
AccessToken은 잘 만들어지는데 payload에 아무것도 안담겨요
로그인 시 받은 accesstoken을 밑에 /user/test의 헤더에 넣었습니다.처음에는 payload에 값이 담겼는데 갑자기 아무것도 안담기네요ㅜㅜ변경사항이 있었던 건 다 돌려봤는데도 도저히 뭐가 문제인지 모르겠어서 남깁니다.뭐가 문제인지도 모르겠어서 코드도 뭘 보여드려야 할 지 모르겠네요ㅜㅜ accesstoekn은 잘 만들어지는데.. 저 accesstoekn으로 UseGuards(AuthGuard('access')) 이 가드를 통과하는 거 아닌가요?validate()까지 간 거 보면 인가는 됐다고 생각했는데 왜 payload에 아무것도 안담기는지 모르겠네요ㅜㅜ
-
해결됨탄탄한 백엔드 NestJS, 기초부터 심화까지
AlreadyHasActiveConnectionError 에러 발생
에러 해결하였습니다..app.module.ts > typeOrmModuleOptions에keepConnectionAlive: true 옵션이 빠져있어 발생한 에러였습니다. 검색해보니 '어플리케이션 종료 시 DB 연결 유지'에 대한 내용인데제가 다른 옵션과 착각하고 주석 처리했었습니다. 현재 옵션 활성화 하였고 e2e 테스트 정상적으로 진행되는거 확인했습니다.const typeOrmModuleOptions = { useFactory: async ( configService: ConfigService, ): Promise<TypeOrmModuleOptions> => ({ namingStrategy: new SnakeNamingStrategy(), // ... keepConnectionAlive: true, }), 검색해보니 beforeEach에 있는 app.init() 메소드에서 어플리케이션을 초기화하며 DB 연결도 초기화되는데,어플리케이션을 재초기화하는 것이지 종료한 적은 없었기에 여전히 'default'라는 이름으로 활성화된 DB 연결이 존재하였고,DB 연결 재초기화 중 'default라는 이름으로 새로운 DB 연결이 실패하였다' 에러가 발생한 것이며 keepConnectionAlive: true 옵션을 줌으로써DB 연결은 어플리케이션의 생명주기와는 별도로 존재하게 되고, 이미 활성화된 DB 연결이 존재하므로 새로운 DB 연결을 시도하지 않는다 라고 합니다..공부가 되었네요. app.e2e-spec.ts의 afterEach 메소드는 제거하였습니다. ============================================================= 안녕하세요 강사님강의따라 진행하다 에러가 발생하여 질문글 남깁니다. 에러 메세지는 아래와 같습니다.[Nest] 26544 - 2023. 11. 25. 오후 11:01:36 ERROR [TypeOrmModule] Unable to connect to the database. Retrying (1)... AlreadyHasActiveConnectionError: Cannot create a new connection named "default", because connection with such name already exist and it now has an active connection session. at AlreadyHasActiveConnectionError.TypeORMError [as constructor] (C:\Users\admin\OneDrive\바탕 화면\typeorm-in-the-nest\src\error\TypeORMError.ts:7:9) at new AlreadyHasActiveConnectionError (C:\Users\admin\OneDrive\바탕 화면\typeorm-in-the-nest\src\error\AlreadyHasActiveConnectionError.ts:8:9) at ConnectionManager.Object.<anonymous>.ConnectionManager.create (C:\Users\admin\OneDrive\바탕 화면\typeorm-in-the-nest\src\connection\ConnectionManager.ts:57:23) at C:\Users\admin\OneDrive\바탕 화면\typeorm-in-the-nest\src\globals.ts:77:35 at step (C:\Users\admin\OneDrive\바탕 화면\typeorm-in-the-nest\node_modules\tslib\tslib.js:143:27) at Object.next (C:\Users\admin\OneDrive\바탕 화면\typeorm-in-the-nest\node_modules\tslib\tslib.js:124:57) at C:\Users\admin\OneDrive\바탕 화면\typeorm-in-the-nest\node_modules\tslib\tslib.js:117:75 at new Promise (<anonymous>) at Object.__awaiter (C:\Users\admin\OneDrive\바탕 화면\typeorm-in-the-nest\node_modules\tslib\tslib.js:113:16) at createConnection (C:\Users\admin\OneDrive\바탕 화면\typeorm-in-the-nest\node_modules\typeorm\globals.js:55:20) [Nest] 26544 - 2023. 11. 25. 오후 11:01:39 ERROR [TypeOrmModule] Unable to connect to the database. Retrying (2)... AlreadyHasActiveConnectionError: Cannot create a new connection named "default", because connection with such name already exist and it now has an active connection session. at AlreadyHasActiveConnectionError.TypeORMError [as constructor] (C:\Users\admin\OneDrive\바탕 화면\typeorm-in-the-nest\src\error\TypeORMError.ts:7:9) at new AlreadyHasActiveConnectionError (C:\Users\admin\OneDrive\바탕 화면\typeorm-in-the-nest\src\error\AlreadyHasActiveConnectionError.ts:8:9) at ConnectionManager.Object.<anonymous>.ConnectionManager.create (C:\Users\admin\OneDrive\바탕 화면\typeorm-in-the-nest\src\connection\ConnectionManager.ts:57:23) at C:\Users\admin\OneDrive\바탕 화면\typeorm-in-the-nest\src\globals.ts:77:35 at step (C:\Users\admin\OneDrive\바탕 화면\typeorm-in-the-nest\node_modules\tslib\tslib.js:143:27) at Object.next (C:\Users\admin\OneDrive\바탕 화면\typeorm-in-the-nest\node_modules\tslib\tslib.js:124:57) at C:\Users\admin\OneDrive\바탕 화면\typeorm-in-the-nest\node_modules\tslib\tslib.js:117:75 at new Promise (<anonymous>) at Object.__awaiter (C:\Users\admin\OneDrive\바탕 화면\typeorm-in-the-nest\node_modules\tslib\tslib.js:113:16) at createConnection (C:\Users\admin\OneDrive\바탕 화면\typeorm-in-the-nest\node_modules\typeorm\globals.js:55:20) FAIL test/app.e2e-spec.ts (10.952 s) AppController (e2e) √ / (GET) (845 ms) hello jest × two plus two is four (5014 ms) ● AppController (e2e) › hello jest › two plus two is four thrown: "Exceeded timeout of 5000 ms for a hook. Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test." 7 | let app: INestApplication; 8 | > 9 | beforeEach(async () => { | ^ 10 | const moduleFixture: TestingModule = await Test.createTestingModule({ 11 | imports: [AppModule], 12 | }).compile(); at app.e2e-spec.ts:9:3 at Object.<anonymous> (app.e2e-spec.ts:6:1) Test Suites: 1 failed, 1 total Tests: 1 failed, 1 passed, 2 total Snapshots: 0 total Time: 11.106 s Ran all test suites. Jest did not exit one second after the test run has completed. This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot 읽어보니 이미 'default'라는 이름의 연결이 존재하고, 현재 활성화 중이므로 같은 이름의 연결을 또 생성할 수 없다는 것 같고,검색해보니 beforeEach 메소드 안에 Test.createTestingModule이 매 테스트마다 DB 연결을 시도하는 상황이라고 나왔습니다.. 하여 아래와 같이 afterEach 메소드를 사용하여 매 테스트마다 어플리케이션을 종료해주도록 코드를 수정하였습니다.describe('AppController (e2e)', () => { let app: INestApplication; beforeEach(async () => { const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule], }).compile(); app = moduleFixture.createNestApplication(); await app.init(); }); // 테스트 2개 이상 사용할 경우 필요한 메소드 afterEach(async () => { await app.close(); }); it('/ (GET)', () => { return request(app.getHttpServer()) .get('/') .expect(200) .expect('typeorm in nest, just coding'); }); describe('hello jest', () => { it('two plus two is four', () => { expect(2 + 2).toBe(4); }); }); // 생략 수정 후 강의에서 진행했던 내용은 모두 완료가 되었는데..이제 궁금한 점은강사님과 코드 내용이 같고 도커나 DB 연결에 대하여 특별히 수정한 내용이 없는데왜 이런 상황이 발생하는 것인지. 버전이 달라 발생한 상황인 것인지.. 그리고 afterEach를 사용하였을때 당장 테스트 진행은 가능하지만 이대로 사용해도 괜찮을지 안좋은 것은 아닌지가 궁금합니다..
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
refresh token db 저장
강의 내용중엔 빠졌지만 refresh token을 db에 저장해야하는것으로 알고있는데요테이블 설계시 refresh 토큰을 User 테이블 내에 칼럼으로 넣을까 생각을했었는데의미가 맞지않는것같아서요 아래처럼 one to one 관계로 해서 관리하는건 올바른 방법일까요?class TokenModel { @PrimaryGenerateKey() @OneToOne(() => UserModel, user => user.refresh) id: string; @Column() refreshToken: string; } class User { ... @OneToOne(() => TokenModel, token => token.id) refresh: TokenModel }
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
GraphQL import 오류
GraphQL 관련된 내용이 뜨는 것 같긴 한데 ObjectType과 Field를 못 찾는 것 같습니다.. yarn add graphql을 해봐도 안되네요
-
해결됨[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
Transaction 파트에서 에러 발생 후 포스트를 정상적으로 생성하지는 않지만 id값은 증가하는데 정상인가요?
안녕하세요 코드팩토리님!! Transaction 파트에서 궁금한게 있어서 질문 드립니다.Transaction 적용후 테스트로 에러 발생해 보니 정상적으로 포스트가 생성되지는 않습니다.그런데 이후 정상적으로 포스트를 한개 생성하니 이전 마지막 포스트가 10이었으면 이번에는 12번으로 생성됩니다.에러 발생후 포스트는 생성되지 않지만 id 값은 증가하는데 정상적인 현상인가요?? 참고로 에러는 코드팩토리님 처럼 중간에 throw new InternalServerErrorException()을 넣고 저장하면 밑에 코드가 전부 지워져서그냥 images[]에 이미지 넣을때 알파벳 몇개 지워서 일부로 에러 발생하는 방식으로 에러 테스트 했습니다.
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
add Database Connection 에서 막혔습니다.
안녕하세요 강사님 add Database Connection 도중 6번째 항목에서 저는 show All Databases나 postgres가 없어서요.. 진행을 못하고 있습니다.
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
compose.yaml 파일 작성시 environment 오류
안녕하세요 강사님 강의를 들으면서 작성중에 다음과 같은 오류가 발생해서 질문드립니다.강의와 동일하게 작성하였으나 string 타입으로 작성해달라고 오류가 뜨는거 같아서요.. 어느부분이 문제인지를 모르겠습니다.
-
해결됨
NestJS 통합테스트 후 데이터 처리
안녕하세요, 저는 Spring에서 Nest로 넘어온 네린이입니다.스프링에서는 통합테스트 작성시에도 데이터베이스에 데이터가 삽입되거나 업데이트 되지않도록 롤백시키는 방법이 존재하는데 Nest에서는 어떻게 해야하나요? 제가 생각하는 방법은 직접 쿼리러너를 통해 afterEach를 통해서 매번테스트후에 롤백을 시키는방법을 생각했습니다.
-
미해결따라하며 배우는 NestJS
repository.ts 에서 method 를 가져 오고 싶은데, 해당 메소드가 없다고 뜨네요
현재, nestjs로 게시판 만들기를 학습 하고 있는데,에러에, 에러에, 에러에, 에러의 연속이네요... 데이터베이스 연결이 안 되는 에러를 계속 보다가 어찌 어찌 해결은 했는데ERROR [TypeOrmModule] Unable to connect to the database. 이젠 메소드를 찾을 수 없다는 에러가 계속 뜨네요...뭐가 문제인 것일까요... 후우 또 열심히 검색을 해봐야겠습니다... // board.repository.ts import { EntityRepository, Repository } from "typeorm"; import { Board } from "./board.entity"; import { CreateBoardDto } from "./dto/create-board.dto"; import { BoardStatus } from "./board-status.enum"; @EntityRepository(Board) export class BoardRepository extends Repository<Board> { async createBoard(createBoardDto: CreateBoardDto) : Promise<Board> { const { title, description } = createBoardDto; const board = this.create({ title, description, status: BoardStatus.PUBLIC }) await this.save(board); return board; } }// boards.service.ts import { Injectable, NotFoundException } from '@nestjs/common'; import { BoardStatus } from './board-status.enum'; import { CreateBoardDto } from './dto/create-board.dto'; import { InjectRepository } from '@nestjs/typeorm'; import { Board } from './board.entity'; import { Repository } from 'typeorm'; // import { BoardRepository } from './board.repository'; @Injectable() export class BoardsService { constructor( @InjectRepository(Board) private boardRepository: Repository<Board>, ) {} createBoard(createBoardDto: CreateBoardDto) : Promise<Board> { return this.boardRepository.createBoard(createBoardDto); } async getBoardById(id: number): Promise <Board> { const found = await this.boardRepository.findOne(id); if(!found) { throw new NotFoundException(`Can't find board with id ${id}`) } return found; }
-
해결됨[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
docker-compose up 명령 실행후에
services.postgres Additional property restrart is not allowed이런 내용이 뜨면서강사님 영상과 같은 로그들이 나오지 않는데 어떻게 하는 것이 좋을까요?
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
new 와 그냥 클래스 차이에 대한 추가 질문
코팩님 강의 잘보고있습니다. :) 'DefaultValuePipe 사용해보기'라는 강의에서 궁금한 것이 있어서 질문드립니다.new와 그냥 클래스는 제가 이해한 바로는 그냥 클래스처럼 넣게 되면 DI를 통한 nest에서 싱글톤 패턴으로 ParseIntPipe를 주입해주는 것이고 new키워드를 붙이게 되면 인스턴스가 생성하게 됨으로 nest에서 DI로 주입해주는 것이 아닌 ParseIntPipe클래스의 인스턴스가 생성되는 방식인가요?감사합니다.
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
파일 업로드 질문
안녕하십니까혹시 graphql을 이용한 이미지 업로드 부분에서포스트맨 말고 클라이언트에서 요청하려고 할 때다른 설정들이 필요한가요?여러 방법들을 해봤는데 모두 안되서 질문 드립니다. await axios.post("http://localhost:5656/graphql", { query: ` mutation { uploadFile(file: ${file}) } `, })const file = files[0] await axios.post("http://localhost:5656/graphql", { query: ` mutation uploadFile($file: Upload!) { uploadFile(file: $file) }, `, variables: { file: file, }, })
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
배열을 스웨거로 작성하는 법을 모르곘어요
퀴즈 4 풀고 있는데 1개 이상의 배열을 스웨거로 작성하는 법을 모르겠습니다.예를 들면[{name:"철수",age:2},{name:"훈이",age:3}] 이런거를 이런 예시를 가지고 2개의 배열로 나타내는 법을 모르겠습니다
-
해결됨[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
[모든 Route 기본 Private로 만들고 IsPublic Annotation 작업하기] IsPublic을 사용하면 RefreshTokenGuard도 무력화되지 않나요?
RBAC까지 다뤄주시다니 정말 흥미로운 내용이었습니다!다만 현재 로직상으로는 RefreshTokenGuard이 적용된 Access 토큰 갱신, Refresh 토큰 갱신 API에 IsPublic을 적용하면 RefreshTokenGuard도 미적용되지 않나요?실제 저 API들을 Access Token으로 호출해보면 Guard가 아니라 Service 단에서 Exception이 발생하는 것 같더라구요.
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
포트폴리오 작성할 때 강의에서 배운대로 적어도 되나요?
포트폴리오 작성하고 있는데 강의에서 배운 내용들로 채워도 되나요? 아니면 선생님이 doc를 직접 찾아보라고 일일히 강의에서 설명하지 않은 내용들을 써야하나요?
-
미해결Slack 클론 코딩[백엔드 with NestJS + TypeORM]
AWS-RDS 사용중인데 createdAt 시간이 실제 시간과 맞지 않습니다.
왼쪽은 엣지 inprivate, 오른쪽은 크롬 시크릿 모드 브라우저입니다.서로의 채팅 입력 시간이 9시간 전으로 표시되고 있습니다. 실제로 서버의 createdAt은 한국 표준시라고는 되어있지만 실제 시간보다 9시간 느린 시간이 저장되었고 entities/channelChats.ts의 설정 내용은 강사님의 깃헙 내용과 동일했습니다. aws - rds에서 확인해본 DB도지역이 ap-northeast-2a, 서울로 잘 지정되어 있었습니다. 혹시 작업 중에 이런 경우 보신 적 있으신가요?어디를 더 살펴봐야 서버에 제대로 된 현재 시간이 저장될 수 있을지 조언 부탁드립니다.