묻고 답해요
156만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
조회 시, select로 일부 필드만 가져올 때 GraphQL 처리
안녕하세요 :)아래 코드와 같이 상품 조회할 때 select를 통해 일부 필드만 가져오도록 해봤습니다.service의 findAll 메서드에서는 유틸리티 타입으로 반환하도록 하였고,resolver에서는 Query 데코레이터에 GraphQL에서 제공하는 PickType으로 반환하게 했는데, 에러가 발생합니다.. (적절한 값이 아니라는 에러 내용)이런 상황에서는 메서드 반환 타입과 GraphQL 타입 처리를 어떻게 해주는 것이 좋은지 감이 잘 안 잡혀서 질문드려요! // products.resolver.ts @Query(() => [PickType(Product, ['id', 'name', 'description'])]) fetchProducts(): Promise<Pick<Product, 'id' | 'name' | 'description'>[]> { return this.productsService.findAll(); }// products.service.ts findAll(): Promise<Pick<Product, 'id' | 'name' | 'description'>[]> { return this.productsRepository.find({ select: ['id', 'name', 'description'], }); }
-
미해결비전공자를 위한 풀스택 맛집지도 만들기 프로젝트!: Front, Back-end 그리고 배포까지
인스턴스 중단 후 재시작
프로젝트를 완성하고 aws 인스턴스 프리티어 사용량이 제한량에 거의 도달해서 항상 켜놓으면 안되겠다고 생각해서 잠깐 중단시켰다가 며칠후에 재시작 시켰는데 재시작 한 이후로 지도상에 핀이 안 보이는데 어떻게 해야할까요? pm2도 해놔서 인스턴스를 중단했다가 재시작한것 때문인거 같은데... mysql을 접속하려 했을때 이런 창이 뜹니다.
-
해결됨[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
섹션 26. 이미지 업로드 - 클래식 방법에서 질문이 있습니다!
안녕하세요!이미지 업로드 클래식 방법을 듣다 막히는 부분이 있어 질문 드립니다! @Post() @UseGuards(AccessTokenGuard) @UseInterceptors(FileInterceptor('image')) postPosts( @User('id') userId: number, @Body() body: CreatePostDto, @UploadedFile() file?: Express.Multer.File, console.log(userId); return this.postsService.createPost(userId, body, file?.filename); }컨트롤러에 해당 셋팅까지 마무리하고 postman으로 요청을 보내려고 시도를 했습니다. 하지만 400에러가 발생하더라고요 ㅠㅠ에러 message는 "Multipart : Malformed part header" 라고 표출이 됩니다. postman의 헤더 설정 문제인가해서 header셋팅하는 쪽 살펴보니 자동으로 header 설정이 되고 있어서 문제는 없는 것 같습니다.. 일단 컨트롤러에 요청자체가 걸리지 않는 것 같습니다ㅠ혹시 어떤 이유 일까요?
-
해결됨Java 마이크로서비스(MSA) 프로젝트 실습
직접 어플리케이션 서버에 요청을 보내면 동작하는데, gateway 서버로 보내면 404가 뜹니다
config-server / eureka-server / gateway-server /그리고 item-service-server 대신에 제가 만드는 rms라는 애플리케이션 서버를 띄웠습니다.게이트웨이 서버를 통해서 http 요청을 보내면 404가 뜨고직접 애플리케이션 서버로 요청을 보내면 잘 동작하는 상태입니다.그래서 config-server의 gateway-server-local.yml 파일에서 spring.cloud.gateway 부분에 문제가 있을거라 추측하고 계속 찾아봤는데... 어떻게 변경해야 할지.. 잘 모르겠어서 질문드립니다. 일단 파일 전체를 공유하겠습니다.config-serverresources.application.ymlspring: application: name: config-server profiles: active: native cloud: config: server: native: search-locations: classpath:/config encrypt: enabled: false server: port: 8080 resources.bootstrap.ymlencrypt: key: IRON0000 resources.config.eureka-server-local.ymllogging: file: name: logs/eureka.log max-size: 500MB max-history: 10 level: root: info org.com.iron.eureka-server: debug spring: application: name: eureka-server server: port: 8761 eureka: instance: hostname: eureka-server client: serviceUrl: defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ register-with-eureka: false fetch-registry: false management: endpoints: web: exposure: include: "*" resources.config.gateway-server-local.ymllogging: file: name: logs/gateway-local.log max-size: 500MB max-history: 10 level: root: info org.hibernate.SQL: debug # org.hibernate.type: trace spring: application: name: gateway-server cloud: gateway: routes: - id: rms uri: lb://rms eureka: instance: prefer-ip-address: true client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:8761/eureka resources.config.rms.ymllogging: file: name: logs/api.log max-size: 500MB max-history: 10 level: root: info org.hibernate.SQL: debug # org.hibernate.type: trace spring: datasource: url: jdbc:h2:tcp://localhost/~/server-iron username: sa password: driver-class-name: org.h2.Driver jpa: hibernate: ddl-auto: none properties: hibernate: show_sql: true format_sql: true default_batch_fetch_size: 1000 #최적화 옵션 mybatis: mapper-locations: mybatis/mappers/*.xml springdoc: default-consumes-media-type: application/json default-produces-media-type: application/json swagger-ui: operations-sorter: alpha disable-swagger-default-url: true display-query-params-without-oauth2: true resources.config.rms-local.ymllogging: file: name: logs/rms-local3.log max-size: 500MB max-history: 10 level: root: info org.hibernate.SQL: debug # org.hibernate.type: trace spring: datasource: url: jdbc:h2:tcp://localhost/~/server-iron username: sa password: '{cipher}' driver-class-name: org.h2.Driver jpa: hibernate: ddl-auto: none properties: hibernate: show_sql: true format_sql: true default_batch_fetch_size: 1000 #최적화 옵션 mybatis: mapper-locations: mybatis/mappers/*.xml springdoc: default-consumes-media-type: application/json default-produces-media-type: application/json swagger-ui: operations-sorter: alpha disable-swagger-default-url: true display-query-params-without-oauth2: true token: expiration_time: 86400000 secret: IRON0000 eureka: instance: instance-id: ${spring.cloud.client.hostname}:${spring.application.instance_id:${random.value}} prefer-ip-address: true client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:8761/eureka eureka-server.ymlresources.bootstrap.ymlspring: application: name: eureka-server profiles: active: local cloud: config: uri: http://localhost:8080 loadbalancer: ribbon: enabled: false gateway-serverresources.bootstrap.ymlserver: port: 8070 spring: application: name: gateway-server profiles: active: local cloud: config: uri: http://localhost:8080 loadbalancer: ribbon: enabled: false management: endpoints: web: exposure: include: refresh, health, beans rmsresources.bootstrap.ymlserver: port: 0 spring: application: name: rms profiles: active: local cloud: config: uri: http://localhost:8080 loadbalancer: ribbon: enabled: false refresh: extra-refreshable: com.zaxxer.hikari.HikariDataSource management: endpoints: web: exposure: include: refresh, health, beans build.gradle 파일들도 올려야할까요...
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
청개구리 기질로 npm을 쓰는 분들을 위한 launch.json 파일 공유
청개구리 기질로 npm으로 하고 싶어서 강의를 따라오다 여기서 막혀서 구글링 삽질로 해결 했던 정보를 공유 해요~// launch.json{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "type": "node", // 세팅의 타입 "request": "launch", // launch 실행하는거, attach 실행되있는거에 붙는거 "name": "Debug NestJS", // 어떤 이름으로 부를건지 "runtimeExecutable": "npm", // 어떤걸로 실행 할건지 node, yarn ... "runtimeArgs": ["run", "start:debug"], // npm run start:dev 에서 npm이 runtime이고 run start:dev가 Args임 "console": "integratedTerminal", // intergratedTerminal은 vscode에서 실행하는 터미널임 "restart": true, // 자동 연결 할건지 "port": 9229, "autoAttachChildProcesses": true // 디버거를 자동으로 process에 붙을지 말지 결정 } ] }
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
vscode의 디버거를 덕분에 알게 되었는데
강의를 다 보고 나니 너무 좋은 기능인것 같고, 실제로 해당 기능을 개발 단계에서 사용 할때는 따로 winston이나 내장 logger나 console.log 필요 없이(production에선 사용) 해당 디버거를 이용해서 하는게 훨씬 좋아 보이는데, 실무에서도 자주 사용 하시나요?
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
상품 등록 API 오류 납니다
ERROR [TypeOrmModule] Unable to connect to the database Retrying (2)... QueryFailedError: Incorrect datetime value: '0000-00-00 00:00:00' for column 'meetingTime' at row 1라고 오류납니다 product.resolver.tsimport { Args, Mutation, Query, Resolver } from '@nestjs/graphql'; import { ProductsService } from './product.service'; import { CreateBoardInput } from '../boards/dto/create-board.input'; import { CreateProductInput } from './dto/create-product.input'; import { Product } from './entities/product.entity'; @Resolver() export class ProductsResolver { constructor( private readonly productsService: ProductsService, // ) {} @Query(() => [Product]) fetchProducts(): Promise<Product[]> { return this.productsService.findAll(); } @Query(() => Product) fetchProduct( @Args('productId') productId: string, // ): Promise<Product> { return this.productsService.findOne({ productId }); } @Mutation(() => Product) createProduct( @Args('createProductInput') createProductInput: CreateProductInput, ): Promise<Product> { // << 브라우저에 결과 보내주는 2가지 방법>> // 1. 등록된 내용이 담긴 객체를 그대로 브라우저에 보내주기 return this.productsService.create({ createProductInput }); // 이걸 선호. 조회 api 요청을 안해도 된다 // 2.결과에서만 간단히 보내주기 // return '정상적으로 상품이 등록되었습니다' } } product.service.tsimport { Args, Mutation, Query, Resolver } from '@nestjs/graphql'; import { ProductsService } from './product.service'; import { CreateBoardInput } from '../boards/dto/create-board.input'; import { CreateProductInput } from './dto/create-product.input'; import { Product } from './entities/product.entity'; @Resolver() export class ProductsResolver { constructor( private readonly productsService: ProductsService, // ) {} @Query(() => [Product]) fetchProducts(): Promise<Product[]> { return this.productsService.findAll(); } @Query(() => Product) fetchProduct( @Args('productId') productId: string, // ): Promise<Product> { return this.productsService.findOne({ productId }); } @Mutation(() => Product) createProduct( @Args('createProductInput') createProductInput: CreateProductInput, ): Promise<Product> { // << 브라우저에 결과 보내주는 2가지 방법>> // 1. 등록된 내용이 담긴 객체를 그대로 브라우저에 보내주기 return this.productsService.create({ createProductInput }); // 이걸 선호. 조회 api 요청을 안해도 된다 // 2.결과에서만 간단히 보내주기 // return '정상적으로 상품이 등록되었습니다' } } productSaleslocation.entity.tsimport { Field, Float, ObjectType } from '@nestjs/graphql'; import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm'; @Entity() @ObjectType() export class ProductSaleslocation { @PrimaryGeneratedColumn('uuid') @Field(() => String) id: string; @Column() @Field(() => String) address: string; @Column() @Field(() => String) addressDetail: string; // // 9자리 중에서 6자리가 소수점 @Column({ type: 'decimal', precision: 9, scale: 6 }) @Field(() => Float) lat: number; @Column({ type: 'decimal', precision: 9, scale: 6 }) @Field(() => Float) lng: number; @Column() @Field(() => Date) meetingTime: Date; } meetingTime graphlql 타입을 맞게 해났는데 왜 오류나는지 모르곘습니다
-
미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
yml 파일 수정 후에는 SecurityConfig 클래스를 삭제해야 하나요?
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> <version>3.0.4</version> </dependency>import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration public class SecurityConfig { @Bean UserDetailsService userDetailsService() { InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(); UserDetails newUser = User.withUsername("user") .password(passwordEncoder().encode("passw0rd")) .authorities("read") .build(); userDetailsManager.createUser(newUser); return userDetailsManager; } @Bean BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } pom.xml에 있는 spring-boot-starter-security를 주석처리하게 되면 SecurityConfig 클래스에서 오류가 발생합니다. 이 클래스는 그대로 주석처리 하면 되는 건가요?
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
3분50초쯤에 오버라이드라고 말씀 하셨는데
Column().d.ts에서 declare로 정의 되어 있는것들을 오버라이드라고 말씀 하셨는데, 인자값에 따라 다른 호출을 하는건 오버로딩이 아닌가해서요!
-
미해결[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
Exception Class 생성문의 추가 질문
안녕하세요. 강사님 답변 감사합니다.답변해 주신 것으로는실무에서도 사용자 정의 예외 클래스를 사용하는 것으로 이해했습니다. 추가로 질문드리고 싶은 것이 있는데첫 번째 질문으로는 사용자 정의 클래스를 사용할 때 상위 예외를 상속할 때 보통 RuntimeException을 상속해서 만드는지 디테일한 Exception을 상속하여 생성하는지 질문드리고 싶습니다! 두 번째 질문으로는 자바의 예외 클래스를 사용할 때보다 사용자 정의 클래스를 생성하여 사용하는 게 답변해 주신 것처럼"직접 예외 클래스를 생성하면 메시지나 처리 제어 등이 가능합니다."라는 장점으로예외 처리를 할 때 사용 빈도가 훨씬 더 많을 것 같다고 개인적으로 생각을 하고 있는데실무에서는 자바의 예외 클래스를 사용하는 것보다는예외 클래스를 직접 생성하여 사용하는 경우가 훨씬 더 많을까요?
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
return false 대신 try catch
function TokenAPI(phNumber){ try { checkPhoneState(phNumber); //휴대폰 상태 점검 } catch (error) { console.log(error); } const token = createToken(); //토큰발급 sendToken(phNumber,token); //휴대폰에 토큰 발송 } function checkPhoneState(phNumber){ if(phNumber.length != 11){ throw new Error("올바르지 않은 번호입니다."); } else if(isNaN(phNumber) != false){ throw new Error("올바르지 않은 번호입니다."); } } function createToken(){ return String(Math.floor(Math.random() * 1000000)).padStart(6,"0"); } function sendToken(phNumber,token){ console.log(phNumber + "번호로 인증번호 " + token + "이 전송되었습니다."); } 이런식으로 try catch 써도 되나요?
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
common.service 의 cursorPaginate 일반화 할때 nextUrl 생성시 질문입니다.
common.service 의 cursorPaginate 일반화 관련 질문입니다.nextUrl 생성할 때 아래와 같이 searchParams 를 생성하는데 이 부분은 일반화 할 수없는건가요?if (nextUrl) { for (const key of Object.keys(dto)) { if (dto[key]) { if ( key !== 'where__id__more_than' && key !== 'where__id__less_than' ) { nextUrl.searchParams.append(key, dto[key]); } } } let key = null; if (dto.order__createdAt === 'ASC') { key = 'where__id__more_than'; } else { key = 'where__id__less_than'; } nextUrl.searchParams.append(key, lastItem.id.toString()); }
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
css 회원가입 실습 질문있습니다!
안녕하세요!강의 수강 시작하고 지금 싸이월드 실습 막 시작한 학생입니다.다름이 아니라 회원가입 부분 실습 마지막 몇 부분을 남기고 막혀서모범코드(?) 같은걸 확인하고 싶은데, 학습자료 부분에가도 싸이월드 코드랑피그마 링크만 안내되어있고 회원가입코드는 안보여서요!일단 이렇게 이미지로 질문을 드려봅니다.남성/여성 라디오버튼을 크기맞추고 가운데정렬까지 했는데 텍스트가 이렇게 세로로 정렬되어 버립니다. 체크박스버튼은 어떻게 손을봐야 할지 모르겠습니다 ㅜ
-
해결됨[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
postgresql 연결실패
docker-compose.yml파일에 아래와같이 작성했습니다.포트번호를 5808로 지정해준 이유는 5432로 지정해서 접속했을때 현재 pc에 설치했던 postgresql과 충돌이 나서 로그인이 안돼서 바꾸어 주었습니다.도커 컴포즈 실행후 postgresql 컨테이너는 정상적으로 실행이 됐으나 nest앱과 postgresql explorer에서도 연결이 되지 않았습니다. 어떻게 해결해야하는지 질문드립니다# 서비스정의 services: postgres: image: postgres:15 # 실행시마다 재시작 restart: always # 도커컴포즈 파일에 존재하는 위치에 실제 데이터를 hostOS에 저장 volumes: # 현재 도커컴포즈 파일이 존재하는 경로 : 이미지안에존재하는 경로 매핑 - ./postgres-data:/var/lib/postgresql/data ports: #hostport:이미지의포트 #5432포트 요청 -> 이미지의 포트로 요쳥 - '5808:5432' environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: '1111' POSTGRES_DB: postgresimport { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { PostsModule } from './posts/posts.module'; import { TypeOrmModule } from '@nestjs/typeorm'; import { PostsModel } from './posts/entities/posts.entity'; @Module({ //다른 모듈을 등록 //forRoot메서드는 typrorm과 nestjs와 연결할떄 사용 (DB) imports: [ PostsModule, TypeOrmModule.forRoot({ //데이터베이스 타입 type: 'postgres', host: '127.0.0.1', port: 5808, username: 'postgres', password: '1111', database: 'postgres', //entities폴더에 작성한 PostsModel 가져오기 entities: [PostsModel], synchronize: true, }), ], controllers: [AppController], providers: [AppService], }) export class AppModule {}
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
해당 강의와 무관한 질문인데
혹시 2편은 언제 올라 오나요? ㅎㅎ바로 구매 하고 싶습니다
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
실제 프로젝트나 현업에서 primary key로 uuid를 사용하지 않아도 괜찮은가요?
uuid를 사용하지 않으면 id 값이 너무 단순해 보이는데 값이 쉽게 예측됨으로써 발생하는 보안 문제는 없을까요..? 실제 현업에서는 uuid를 사용하는지 사용하지 않는지 궁금하네요.. 그리고 uuid를 more than을 통해 값을 비교햐여 pagination을 구현하는 것이 가능한가요?
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
저만 이런 에러 뜨는건지 모르겠는데, 영상 안나와서
해당 영상도 또 안나와서 이상해서 개발자도구 켜보니까/course/lecture?courseSlug=nestjs-%EB%B0%B1%EC%97%94%EB%93%9C-%EC%99%84%EC%A0%84%EC%A0%95%EB%B3%B5-%EB%A7%88%EC%8A%A4%ED%84%B0-%ED%81%B4%EB%9E%98%EC%8A%A4-1&unitId=184136:1 Access to fetch at 'https://vod.inflearn.com/key/9d2b2df0-4061-42e6-a634-42fb7a946b91/68?key=d6303460076ac117c072323d06f3d269d6bd8dfde7e4a95ba3292cce2fdc879f' from origin 'https://www.inflearn.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.vod.inflearn.com/key/9d2b2df0-4061-42e6-a634-42fb7a946b91/68?key=d6303460076ac117c072323d06f3d269d6bd8dfde7e4a95ba3292cce2fdc879f:1 Failed to load resource: net::ERR_FAILED 인프런 자체 에러가 같은데 원인을 모르겠습니다.
-
미해결[코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core
0:41초부터 무한 로딩 되면서 영상 이 안나오네요.
제 인터넷 문제인줄 알았으나, 영상이 문제 인것 같습니다.0:41초 되면 안나옵니다.다른 영상들은 문제 없이 잘나옵니다.
-
미해결[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
안녕하세요 강의 코드에 대해 질문이 있습니다.
안녕하세요 강의를 만족하며 보고있습니다.제가 강의를 수강하면서 모르는 부분만 보거나, 필요한 내용들을 그때마다 찾아서 공부하고 있습니다.하지만 강의가 차례로, 순서대로 해야만 학습 가능한 부분들이있어 공부 하기가 어려운 점이 많습니다. 또 전체적인 코드로 한눈에 흐름을 파악하여 해당 강의 내용을 보고 싶을 때도 많은데, 차례로 강의를 따라가야지만 전체를 볼 수 있기 때문에 어렵습니다.그래서 세션을 공부하기 위한 베이스 코드나, 강의를 하고 난 완료된 코드를 받고 싶은데 부탁드리겠습니다.감사합니다.
-
해결됨[개정판 2023-11-27] Spring Boot 3.x 를 이용한 RESTful Web Services 개발
Exception Class 생성 문의
안녕하세요예외 클래스 생성하는 것에 대해서 질문드립니다.일반적으로 API를 클라이언트에서 호출 했을 때Exception이 발생하면실무에서는 보통 해당 강의와 같이 Exception을 직접 만들어서 사용하는지 여쭤보고자 합니다.