묻고 답해요
160만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결따라하며 배우는 NestJS
저는 왜 import가 자동으로 되지 않을까요?
혹시 관련 모듈이나 단축키가 있을까아ㅛ?이번 강의에서는 BaseEntity가 영상에서 보면 자동으로 import가 되던데 저는 되지 않습니다;
-
미해결따라하며 배우는 NestJS
typeorm 버젼 0.3.x 문제로 인한 deperaciated 문제 쉽지 않네여
이거 강의 다시 찍어주시면 안되나여 인터넷 자료만 보고 따라 하기 넘 어렵 ; stackover flow 에서 뭐라는건지 잘몰겠습니다 ㅋㅋ; https://stackoverflow.com/questions/71557301/how-to-workraound-this-typeorm-error-entityrepository-is-deprecated-use-repo
-
미해결탄탄한 백엔드 NestJS, 기초부터 심화까지
DI(의존성 주입)을 왜 해야하나요?
cats.service.ts 파일import { Injectable } from '@nestjs/common'; @Injectable() export class CatsService { getAllCats(): string { return 'get all cats1'; } } export const getAllCatsTest = () => { return 'get all cats2'; }; cats.controller.ts 파일import { CatsService } from './cats.service'; import * as catsService2 from './cats.service'; import { Controller, Get, } from '@nestjs/common'; @Controller('cats') export class CatsController { constructor(private catsService: CatsService) {} @Get() getAllCat() { return this.catsService.getAllCats(); } @Get('2') getAllCat2() { return catsService2.getAllCatsTest(); } } Dependency Injection을 사용해야하는 이유가 명확히 이해가 안됩니다. A라는 클래스에서 B라는 클래스를 인스턴스화 (new 키워드 사용) 했을 때, A클래스가 B클래스에 대해서 의존성이 발생하고만약에 B 클래스의 수정점이 발생한다면, A클래스도 수정해줘야하는 부분은 인지를 했습니다. 그런 경우에 변화를 유연하게 대응하기 위해 A클래스에서 직접 인스턴스화를 하는것이 아니라,인스턴스화된 클래스를 주입받아 사용만 하는걸 Dependency Injection(의존성 주입)으로 이해했습니다. 하지만, import해서 쓰면 되는걸 왜 굳이 의존성주입이라는 형태로 사용해야하는지 이해를 못했습니다. 제가 위에 예시로 작성한 service 파일과 controller를 보시면,getAllCat()는 의존성 주입해서 사용한거고, getAllCat2는 import한 서비스를 사용한겁니다. 어떠한 이유에서 의존성 주입의 개념을 사용해야하는지 명쾌하게 알고 싶습니다.
-
미해결Slack 클론 코딩[백엔드 with NestJS + TypeORM]
Class-Validator MODULE_NOT_FOUND 에러
강의를 잘 따라 가면서 공부를 하고 있는데 강좌에 나와있는대로 class-validator 을 npm -i class-validator 을 설치 후 nest를 실행하니 nest 에서 Cannot find module 'class-validator/types/decorator/decorators' 라는 에러를 나타냅니다. 혹시 몰라서 API 공식문서 에 있는 npm i class-validator class-transformer 을 다시 설치를 해보아도 같은 에러를 나타내는데 이럴 경우 어디서 확인을 해보아야 할까요?혹시 몰라서 package.json 을 살펴 보았습니다만 dependencies 내에 설치가 되어있는것으로 나왔습니다.
-
해결됨따라하며 배우는 NestJS
delete({ id, user}) 안되는 문제
저는 id => { id, user} 로 변경하니 type 에러가 발생했습니다.그래서(mac기준) 커맨드 + delete 함수 클릭criteria 변수에 { id:number, user:User} 타입 추가저장이 방법으로 해결했습니다.별거 아니지만 저는 엄청 헤매서 공유차 남깁니다..!
-
미해결탄탄한 백엔드 NestJS, 기초부터 심화까지
혹시 저처럼 s3에 업로드할 때 아무 이미지도 안 올라시는 분들이 있으면 봐주세요
혹시 저처럼 buffuer가 찍히지 않으신 분들은storage에 multer.memoryStage()를 추가하면 buffer가 찍히실 겁니다.https://github.com/expressjs/multer#memorystorage
-
미해결탄탄한 백엔드 NestJS, 기초부터 심화까지
왜 env파일을 읽어오지 못하는지 모르겠습니다.
log를 찍어봤는데 env가 undifine으로 아예 불러오지를 못하는데 제가 간과한게 있을까요?
-
미해결Slack 클론 코딩[백엔드 with NestJS + TypeORM]
스웨거 문서를 PickType으로 만들 수 있나요?
1. Users.ts(엔티티) import { Column, CreateDateColumn, DeleteDateColumn, Entity, Index, JoinTable, ManyToMany, OneToMany, PrimaryGeneratedColumn, UpdateDateColumn, } from 'typeorm'; import { ChannelChats } from './ChannelChats'; import { ChannelMembers } from './ChannelMembers'; import { Channels } from './Channels'; import { DMs } from './DMs'; import { Mentions } from './Mentions'; import { WorkspaceMembers } from './WorkspaceMembers'; import { Workspaces } from './Workspaces'; import { IsEmail, IsNotEmpty, IsString } from 'class-validator'; import { ApiProperty } from '@nestjs/swagger'; @Index('email', ['email'], { unique: true }) @Entity({ schema: 'sleact', name: 'users' }) export class Users { @PrimaryGeneratedColumn({ type: 'int', name: 'id' }) id: number; @ApiProperty({ example: `aaa123@google.com`, description: '이메일', required: true, }) @IsEmail() @IsNotEmpty() @Column('varchar', { name: 'email', unique: true, length: 30 }) email: string; @ApiProperty({ example: `홍길동`, description: '닉네임', required: true, }) @IsString() @IsNotEmpty() @Column('varchar', { name: 'nickname', length: 30 }) nickname: string; @ApiProperty({ example: `123123`, description: '비밀번호', required: true, }) @IsString() @IsNotEmpty() @Column('varchar', { name: 'password', length: 100, select: false }) password: string; @CreateDateColumn() createdAt: Date; @UpdateDateColumn() updatedAt: Date; @DeleteDateColumn() deletedAt: Date | null; @OneToMany(() => ChannelChats, (channelchats) => channelchats.User) ChannelChats: ChannelChats[]; @OneToMany(() => ChannelMembers, (channelmembers) => channelmembers.User) ChannelMembers: ChannelMembers[]; @OneToMany(() => DMs, (dms) => dms.Sender) DMs: DMs[]; @OneToMany(() => DMs, (dms) => dms.Receiver) DMs2: DMs[]; @OneToMany(() => Mentions, (mentions) => mentions.Sender) Mentions: Mentions[]; @OneToMany(() => Mentions, (mentions) => mentions.Receiver) Mentions2: Mentions[]; @OneToMany( () => WorkspaceMembers, (workspacemembers) => workspacemembers.User, ) WorkspaceMembers: WorkspaceMembers[]; @OneToMany(() => Workspaces, (workspaces) => workspaces.Owner) OwnedWorkspaces: Workspaces[]; @ManyToMany(() => Workspaces, (workspaces) => workspaces.Members) @JoinTable({ name: 'workspacemembers', joinColumn: { name: 'UserId', referencedColumnName: 'id', }, inverseJoinColumn: { name: 'WorkspaceId', referencedColumnName: 'id', }, }) Workspaces: Workspaces[]; @ManyToMany(() => Channels, (channels) => channels.Members) @JoinTable({ name: 'channelmembers', joinColumn: { name: 'UserId', referencedColumnName: 'id', }, inverseJoinColumn: { name: 'ChannelId', referencedColumnName: 'id', }, }) Channels: Channels[]; } 2. join.request.dto import { PickType } from '@nestjs/mapped-types'; import { Users } from '../../entities/Users'; export class JoinRequestDto extends PickType(Users, [ 'email', 'nickname', 'password', ] as const) {} 3. user.dto import { JoinRequestDto } from './join.request.dto'; import { ApiProperty } from '@nestjs/swagger'; export class UserDto extends JoinRequestDto { @ApiProperty({ example: `1`, description: '아이디', required: true, }) id: number; } 4. users.controller import { Body, Controller, ForbiddenException, Get, NotFoundException, Post, Req, Res, UseGuards, UseInterceptors, } from '@nestjs/common'; import { UsersService } from './users.service'; import { JoinRequestDto } from './dto/join.request.dto'; import { User } from '../common/decorators/user.decorator'; import { UndefinedToNullInterceptor } from '../common/interceptors/undefinedToNull.interceptor'; import { LocalAuthGuard } from '../auth/local-auth.guard'; import { NotLoggedInGuard } from '../auth/not-logged-in.guard'; import { LoggedInGuard } from '../auth/logged-in.guard'; import { ApiCookieAuth, ApiOperation, ApiResponse, ApiTags, } from '@nestjs/swagger'; import { Users } from '../entities/Users'; import { UserDto } from './dto/user.dto'; @ApiTags('USERS') @UseInterceptors(UndefinedToNullInterceptor) @Controller('api/users') export class UsersController { constructor(private readonly usersService: UsersService) {} @ApiCookieAuth('connect.sid') @ApiOperation({ summary: '내 정보 가져오기' }) @ApiResponse({ type: UserDto, }) @Get() async getMyProfile(@User() user: Users) { return user || false; } @ApiResponse({ status: 500, description: 'Server Error..', }) @ApiResponse({ status: 200, description: '성공!', }) @ApiOperation({ summary: '회원가입' }) @UseGuards(NotLoggedInGuard) @Post() async join(@Body() body: JoinRequestDto) { const user = this.usersService.findByEmail(body.email); if (!user) { throw new NotFoundException(); } const result = await this.usersService.join( body.email, body.nickname, body.password, ); if (result) { return 'ok'; } else { throw new ForbiddenException(); } } @ApiResponse({ status: 200, description: '성공', type: UserDto, }) @ApiOperation({ summary: '로그인' }) @UseGuards(LocalAuthGuard) @Post('login') async login(@User() user: Users) { return user; } @ApiCookieAuth('connect.sid') @ApiOperation({ summary: '로그아웃' }) @UseGuards(LoggedInGuard) @Post('logout') async logout(@Req() req, @Res() res) { req.logOut(); res.clearCookie('connect.sid', { httpOnly: true }); res.send('ok'); } } ---------------------------- 스웨거 문서 1. Dto 관련 스키마 2. usersDto를 사용한 결과 3. joinRequestDto를 사용한 결과 마지막 결과 쪽에 제가 생각한 것은 빈칸이 아니라{ email : "aaa123@google.com" nickname: "홍길동" passwork: "123123"} 이었는데 빈칸으로 나오네요.. 혹시 잘못한 부분이 있을까요?
-
미해결탄탄한 백엔드 NestJS, 기초부터 심화까지
jwt passport 질문입니다
2종류의 user테이블a_user, b_user 테이블을 가지고 있는데 각 유저테이블에 대해 jwt 검증을 나눠서 하고싶은데..아무리해도 안되는데 팁이 있을까요
-
미해결따라하며 배우는 NestJS
EntityRepository 가 deprecated 됐다고 나옵니다.
캡처한것처럼 deprecate됐다고 나오는데 그냥 이후 수업 진행해도 되는건가요?
-
미해결탄탄한 백엔드 NestJS, 기초부터 심화까지
cat repository에서의 오류
async existsByEmail(email: string): Promise<boolean> { try { const result = await this.catModel.exists({ email }); return result; } catch (error) { throw new HttpException('db error', 400); } } 에서 return result부분에서 오류가 발생합니다. src/cats/cats.repository.ts:20:7 - error TS2322: Type 'Pick<Document<Cat, any, any>, "_id">' is not assignable to type 'boolean'. 20 return result; ~~~~~~~~~~~~~~exists() 따라가 보면 리턴타입이 boolean이 아닌거 같은데 어떤 부분을 확인해 보면 좋을까요? console.log로 result를 찍어보면 { _id: new ObjectId~~~} 가 나옵니다.
-
미해결Slack 클론 코딩[백엔드 with NestJS + TypeORM]
제로초님 질문드리고싶습니다. 이런문제는 왜발생한건지 파일 캡쳐합니다 도저히 이해가 안돼네요 undefined property verify
import { Injectable, ExecutionContext, HttpException, HttpStatus, } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; import { JwtService } from '@nestjs/jwt'; @Injectable() export class JwtAuthGuard extends AuthGuard('jwt') { constructor( private readonly jwtService: JwtService, // @Inject(forwardRef(() => AdminsService)) // private readonly adminsService: AdminsService, ) { super(); } canActivate(context: ExecutionContext) { const request = context.switchToHttp().getRequest(); const { authorization } = request.headers; if (authorization === undefined) { throw new HttpException('Token 전송 안됨', HttpStatus.UNAUTHORIZED); } //const token = authorization.replace('Bearer ', authorization); const token = authorization.replace('Bearer ', ''); //console.log(token, 'token!!!'); request.user = this.validateToken(token); return true; } validateToken(token: string) { const secretKey = process.env.SECRET ? process.env.SECRET : 'dev'; try { const data = this.jwtService.verify(token, { secret: secretKey, }); console.log(data, '11번가데이터'); return data; } catch (e) { switch (e.message) { // 토큰에 대한 오류를 판단합니다. case 'INVALID_TOKEN': case 'TOKEN_IS_ARRAY': case 'NO_USER': throw new HttpException('유효하지 않은 토큰입니다.', 401); case 'EXPIRED_TOKEN': throw new HttpException('토큰이 만료되었습니다.', 410); default: console.trace(e); // console.log('광섭짱과 함께하는 코딩공부',) throw new HttpException('서버 오류입니다.', 500); } } } } 이부분은 jwt.guard.ts 입니다 저 빨간줄에서 Trace: TypeError: Cannot read properties of undefined (reading 'verify') 이렇게 나오는데 왜 저렇게 나오는건지 도저히 모르겠네요 해당 토큰값도 잘 받아와서 verify 를 이용해 토큰 유효성 검사를 진행하려하는데 그부분에서 에러가 계속 납니다... 도와주세요
-
해결됨탄탄한 백엔드 NestJS, 기초부터 심화까지
PositiveIntPipe 생성할때 @Injectable() 사용한 이유
안녕하세요! 강의 잘듣고있습니다.!! PositiveIntPipe pipe를 만들때도 의존성 주입을 해야하기 때문에 @Injectable()를 사용하신건가요?? 만약 맞다면 사용한 이유가 궁금합니다.!!( @Injectable 를빼도 작동이 잘되고 파이프도 의존성을 주입해야하나? 라는 궁금증이 있어서 남깁니다!) 감사합니다!
-
미해결따라하며 배우는 NestJS
ERROR [ExceptionHandler] No repository for "BoardRepository" was found.
안녕하세요. 데이터베이스를 이용한 CRUD 구현 > 게시물 생성하기 를 들으면서 service와 controller 코드를 고치고 npm run start:dev 실행을 하니 아래와 같은 오류가 뜹니다. 똑같이 코드를 보며 하고있는데 아래와 같은 오류가 뜨는 이유를 알 수 있을까요?? ERROR [ExceptionHandler] No repository for "BoardRepository" was found. Looks like this entity is not registered in current "default" connection? RepositoryNotFoundError: No repository for "BoardRepository" was found. Looks like this entity is not registered in current "default" connection? at RepositoryNotFoundError.TypeORMError [as constructor] (/Users/Desktop/nestjs_crud/src/error/TypeORMError.ts:7:9) at new RepositoryNotFoundError (/Users/Desktop/nestjs_crud/src/error/RepositoryNotFoundError.ts:10:9) at EntityManager.getRepository (/Users/Desktop/nestjs_crud/src/entity-manager/EntityManager.ts:964:19)
-
미해결탄탄한 백엔드 NestJS, 기초부터 심화까지
mongodb 연결 불가 문제
안녕하세요. .env에 MONGODB_URI를 못 읽어서 계속 mongodb connect 실패가 발생하고 있습니다. 혹시나 하여 app.modules.ts 에서 @Modules 앞 뒤로 MONGODB_URI를 콘솔로 찍어봤는데 @Modules 전에는 값이 안나오고 이후에는 잘 출력되는데요. 혹시 추가로 확인해야할 부분이 있을까요? 감사합니다.
-
미해결탄탄한 백엔드 NestJS, 기초부터 심화까지
common entity 상속 시 컬럼 순서 문제
안녕하세요 typeorm 강의에서 쓰신 common entity를 상속하는 코드를 사용하면 위와 같이 컬럼 순서가 나오는데 이렇게 되면 가독성이 안좋아서 컬럼 순서를 바꿔보려 했습니다. 검색해보니 엔티티를 상속했을때 컬럼 순서를 바꿀수 없다고 합니다. https://www.mrlatte.net/code/2020/11/03/typeorm-entity-inheritance.html 실무에서는 어떻게 사용하시는지 궁금합니다.
-
미해결따라하며 배우는 NestJS
BoardsController 못불러와요 ㅜ_ㅜ
안녕하세요, controller까지 작성하고 npm run start:dev로 테스트시 빈배열을 못불러오고 {"statusCode":404,"message":"Cannot GET /boards","error":"Not Found"} 통신이 안되네요 ㅜ_ㅜ 터미널을 보니, 모듈까지 불러오고 컨트롤러는 못불러옵니다ㅜㅜ MAPPED{/borads, GET} route도 못불러오구요.. 그냥 모듈까지 불러오고 스타트가 되는데 어떻게 해야할까요 ㅜㅜ?
-
미해결Slack 클론 코딩[백엔드 with NestJS + TypeORM]
핫 리로딩 질문
제로초님의 강의를 듣고 혼자 nestjs 개인 프로젝트를 해보려고 개발환경을 세팅하였습니다. 좋은강의 너무 감사드립니다. 세팅을 하던 중 핫 리로딩이 되지 않아 질문드립니다. nestjs 공식문서를 보고 핫 리로딩을 설정하였고, 파일을 수정하면 Error: No such label 'emitAssets' for WebpackLogger.timeEnd() 위와같은 에러가 나오며 실행이 종료됩니다. \Desktop\projects\github_visualization\backend\node_modules\webpack\lib\logging\Logger.js:123 throw new Error(`No such label '${label}' for WebpackLogger.timeEnd()`); 검색을 해보니 webpack 플러그인 문제라고 하는데, 해결 방법을 모르겠어서 질문드립니다.
-
미해결Slack 클론 코딩[백엔드 with NestJS + TypeORM]
NestJs, Apollo Federation 관련 질문 입니다.
nestjs를 리용하여 microservice를 만들고 있는데 gateway를 통하여 하위앱들에 접근하고 있습니다. applications- app에서 정의한 스키마 schoolyear.entity.ts를 users-app, students-app등 다른 여러 app 들에서 사용하려고 합니다. //application-app @ObjectType() @Directive( '@key(fields: "school_year_id, date_begin, date_end")', ) @Entity({ name: 'mth_schoolyear' }) export class SchoolYear extends BaseEntity { @Column() @Field(() => ID, { nullable: true }) @PrimaryGeneratedColumn() school_year_id?: number; @Column() @Field(() => Date, { nullable: true }) date_begin: Date; @Column() @Field(() => Date, { nullable: true }) date_end: Date; } //users-app @ObjectType() @Directive('@extends') @Directive( '@key(fields: "school_year_id , date_begin, date_end")', ) @Entity({ name: 'mth_schoolyear' }) export class SchoolYear extends BaseEntity { @Column() @Field(() => ID, { nullable: true }) @PrimaryGeneratedColumn() @Directive('@external') school_year_id?: number; @Column() @Field(() => Date, { nullable: true }) @Directive('@external') date_begin: Date; @Column() @Field(() => Date, { nullable: true }) @Directive('@external') date_end: Date; } //students-app @ObjectType() @Directive('@extends') @Directive( '@key(fields: "school_year_id , date_begin, date_end")', ) @Entity({ name: 'mth_schoolyear' }) export class SchoolYear extends BaseEntity { @Column() @Field(() => ID, { nullable: true }) @PrimaryGeneratedColumn() @Directive('@external') school_year_id?: number; @Column() @Field(() => Date, { nullable: true }) @Directive('@external') date_begin: Date; @Column() @Field(() => Date, { nullable: true }) @Directive('@external') date_end: Date; } 1. @Directive(@key(fields)) 와 @Directive('@external') 사이에 어떤 관계가 있는지? @Directive('@external')가 정의된 모든 field를 @Directive(@key(fields))에 정의해야 합니까? 2. Users-app에서 정의한 external field "date_begin", "date_end"가 stuents-app에도 중복존재하는데 오유가 아닙니까?
-
미해결따라하며 배우는 NestJS
findOne(id) 에서 에러가 발생한 경우 해결법
# Info 강의 업로드 연도(2021) 와 수강 연도(2022) 사이에 TypeORM 의 버전이 달라서, Repository.findOne() 메서드의 구성이 달라진 것 같다고 생각합니다.강의 대로 코드를 작성하면 후술할 에러가 발생하는데, 해당 부분을 해결하고 나서, 다른 수강생 분들 도 이런 문제를 겪을까 생각되어서 따로 글로 남기게 되었습니다. ## 문제 세 줄 요약 1. fineOne( id) 를 하면 에러가 발생 2. 관련 레퍼런스가 없어서 TypeORM docs 확인 3. fineOneBy({id}) 로 에러 해결 (2022-03-30) 자세한 내용은 ### 해결방법, ### 참고문서, ### 초기질문 참고해주세요.깃 : unchaptered/22-03-nestjs-board: Nest.JS (github.com) ### 해결방법 2022년 3월 30일 기준으로, this.boardsRepository.findOne( id ); 위와 같이 입력을 했는데 에러가 발생했다면, 해당 부분을 다음의 코드로 교체해서 해결할 수 있습니다. this.boardsRepository.fineOneBy({ id }); ### 참고문서 아래 페이지에서 Ctrl + F 로 fineOne 혹은 fineOneBy 를 검색해서 확인하시면 됩니다.TypeORM - Amazing ORM for TypeScript and JavaScript (ES7, ES6, ES5). Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms. ### 초기 질문 boards.service.ts 의 getBoardById() 에서 this.boardsRepository.fineOne(id); 를 하면 id 에 붉은 경고가 다음과 같이 발생하고 있습니다. 혹시 해당 부분이 왜 문제가 되는지 알 수 있을까요? 정크 데이터까지만 푸쉬 해놓았지만, node_module 버전 문제일까 싶어서 깃 허브 링크도 최하단에 올려놓겠습니다. 위의 에러가 발생하는 해당 코드입니다. async getBoardById(id: number): Promise<Board> { const found = await this.boardsRepository.findOne(id); if (!found) throw new NotFoundException(`Can't find Board by ${id}`); return found; } 엔티티 import { BaseEntity, Column, PrimaryColumn, PrimaryGeneratedColumn } from "typeorm"; import { BoardStatus } from "./board-status.enum"; export class Board extends BaseEntity { @PrimaryGeneratedColumn() id: number; @Column() title: string; @Column() description: string; @Column() status: BoardStatus; } baords.repository.ts import { EntityRepository, Repository } from "typeorm"; import { Board } from "./entity/board.entity"; @EntityRepository(Board) export class BoardsRepository extends Repository<Board> { } 깃허브 : unchaptered/22-03-nestjs-board: Nest.JS (github.com)