NestJS 및 Graphql 설정
프론트엔드 지식으로 백엔드 배우기
안녕하세요 여러분, 제 블로그에 다시 오신 것을 환영합니다 .
나는 당신이 모두 안전하고 이 블로그가 당신을 건강하게 찾길 바랍니다 ❤️.
목차
· 소개
· 프로젝트 설치 및 설정
· 리소스 생성
· 파일 유형 및 중요성
∘ module.ts
∘ entities/entity.ts
∘ resolver.ts / controller.ts
∘ service.ts ∘ graphql
∘ dto/input .ts
소개
주요 주제를 시작하기 전에 NestJS에 대해 알아봅시다.
NestJS는 Typescript와 Javascript를 모두 지원하는 Node 프레임워크입니다.
백엔드에서 오는 사람들은 Spring 프레임워크와 유사하다는 것을 알 수 있습니다.
우리와 같은 프런트 엔드 사용자에게 JS/TS로 작성할 수 있는 프레임워크로 API를 만드는 것은 매력적이며 이 프레임워크를 탐색하면서 정말 많은 것을 배웠습니다.
Node를 사용하여 API를 만들 수 없는 것은 아니지만 NestJS를 사용하면 Typescript 및 Javascript에서 API를 쉽게 만들 수 있습니다.
이 블로그는 NestJS를 시작하고 Graphql로 API를 생성하는 것으로 취급할 수 있습니다.
프로젝트 설치 및 설정
# Step 1: Install NestJs globally in your local machine
npm i -g @nestjs/cli
# Step 2: Create a new Project
nest new project-name
# Step 3: Choose your Package Manager
? Which package manager would you ❤️ to use? (Use arrow keys)
❯ npm
yarn
pnpm
# Step 4: Wait for the packages to get installed in your machine.
Note: NestJS application starts from main.ts
GraphQL 라이브러리 설치
# Step 5: Install Graphql libraries
npm i @nestjs/graphql @nestjs/apollo graphql apollo-server-express
import { ApolloDriver } from '@nestjs/apollo';
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { join } from 'path';
@Module({
imports: [
GraphQLModule.forRoot({
driver: ApolloDriver,
typePaths: ['./**/*.graphql'],
definitions: {
path: join(process.cwd(), 'src/graphql.schema.ts'),
},
}),
],
controllers: [],
providers: [],
})
export class AppModule {}
NestJS와 Angular는 유사한 프로젝트 구조를 공유합니다. 두 가지 방법으로 자원을 생성할 수 있습니다.
- 모듈, 리졸버, dto, 컨트롤러 등과 같은 파일을 수동으로 생성합니다.
- 명령을 사용하여 모듈 생성
# Creating modules using command
nest generate resource resource-name
(OR)
nest g resource resource-name
# Choose your transport layer e.g. as we are using graphql go with either 2 or 3
? What transport layer do you use? (Use arrow keys)
❯ REST API
GraphQL (code first)
GraphQL (schema first)
Microservice (non-HTTP)
WebSockets
# Prompts to generate CRUD Operations for your resource
? Would you like to generate CRUD entry points? (Y/n)
Code First:
Our code drives our development, Schema gets created later based on our code.
Schema First:
Based on Schema, code is developed.
파일을 생성하는 다른 방법
# Generating the module file of your resource
nest g mo module-name
# Generating controllers, resources, etc
nest g co controller-name
# Generating service file
nest g s service-name
이제 리소스가 생성되었으므로 해당 파일이 무엇이며 왜 필요한지 이해하겠습니다.
module.ts
애플리케이션에 대한 항목으로 main.js가 있으므로 리소스에 대한 진입점도 module.ts입니다. 리소스의 다른 모든 파일은 여기에 정의됩니다.
# Example module.ts
import { Module } from '@nestjs/common';
import { CarService } from './car.service';
import { CarResolver } from './car.resolver';
@Module({
providers: [CarResolver, CarService]
})
export class CarModule {}
이 폴더는 데이터베이스에서 생성되어야 하는 테이블에만 적용됩니다. Postgres 데이터베이스에서 테이블을 생성하려는 경우 이 특정 파일에서 정의할 수 있는 모든 열, 해당 유형 및 기본 키를 지정할 수 있습니다.
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity('car-table')
export class Car {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column('varchar', { length: 500 })
name: string;
}
이 파일은 API 엔드포인트에만 적용됩니다.resolver.ts - When we use graphql as transport layer.
controller.ts- When we use REST as transport layer.
import { Resolver, Query, Mutation, Args } from '@nestjs/graphql';
import { CarService } from './car.service';
import { CreateCarInput } from './dto/create-car.input';
import { UpdateCarInput } from './dto/update-car.input';
@Resolver('Car')
export class CarResolver {
constructor(private readonly carService: CarService) {}
@Mutation('createCar')
create(@Args('createCarInput') createCarInput: CreateCarInput) {
return this.carService.create(createCarInput);
}
@Query('car')
findAll() {
return this.carService.findAll();
}
@Mutation('updateCar')
update(@Args('updateCarInput') updateCarInput: UpdateCarInput) {
return this.carService.update(updateCarInput.id, updateCarInput);
}
}
실제 데이터베이스 연결 및 비즈니스 로직이 여기에 배치됩니다. 이것은 리졸버와 연결될 것입니다.
import { Injectable } from '@nestjs/common';
import { CreateCarInput } from './dto/create-car.input';
@Injectable()
export class CarService {
create(createCarInput: CreateCarInput) {
return 'This action adds a new car';
}
findAll() {
return `This action returns all car`;
}
}
이 파일에는 요청 유형과 반환되는 응답 유형과 같은 모듈의 스키마가 포함되어 있습니다.
type Car {
id: ID
name: String
}
input CreateCarInput {
name: String!
}
type Query {
car: [Car]!
car(id: Int!): Car
}
type Mutation {
createCar(createCarInput: CreateCarInput!): Car!
}
여기에 우리의 마지막 파일이 있습니다. 이 파일은 리소스에서 사용되는 입력에 따라 다릅니다.
import { Field, ObjectType } from '@nestjs/graphql';
@ObjectType()
export class CreateCarDto {
@Field() readonly id?: string;
@Field() readonly name: string;
}
여기 있습니다. 이 블로그의 모든 것입니다.
모두가 이 블로그를 좋아했으면 좋겠습니다.
마음에 든다면 박수를 치고
친구와 공유하세요.
다음 블로그에서는 데이터베이스 연결과 API 생성에 대해 살펴보겠습니다.
동일하게 계속 지켜봐주십시오…
Frontend에 대한 더 흥미로운 콘텐츠를 보려면 저를 팔로우하세요 .
모두 감사합니다 .
다음 시간까지,
Happy Learning ✍️
Abhishek Kovuri , UI 개발자

![연결된 목록이란 무엇입니까? [1 부]](https://post.nghiatu.com/assets/images/m/max/724/1*Xokk6XOjWyIGCBujkJsCzQ.jpeg)



































