이전 글에 이어집니다.
우선 이전 포스팅 처럼 컨트롤러에 데이터 처리를 하는 것은 올바르지 않다.
물론 프로젝트의 의미나 방향성 기타 등등을 고려하면 그렇지 않을 수 있겠지만,
이번 시간에서는 보통 MVC에서 서비스를 생성하고, 그 서비스에 데이터 처리 로직을 작성하는 (컨트롤러는 기본 라우팅과 발리데이션 및 Reqeust 처리 등등을 할 예정이다.) 법을 적어보려고 한다.
nest g service cats
해당 명령어를 칠 경우 /src/cats/ 경로에 service.ts 파일이 생긴다.
import { Injectable } from '@nestjs/common';
@Injectable()
export class CatsService {}
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CatsController } from './cats/cats.controller';
import { CatsService } from './cats/cats.service';
@Module({
imports: [],
controllers: [AppController, CatsController],
providers: [AppService, CatsService],
})
export class AppModule {}
서비스가 생기면서 AppModule에 CatsService가 import 되고, 추가되어 있는 것을 볼 수 있다.
이제 컨트롤러에 있는 CRUD를 서비스에 옮기고, 컨트롤러는 서비스에 맵핑해보겠다.
import { Body, Param, Controller, Delete, Get, Post, Put } from '@nestjs/common';
import { CatsService } from './cats.service';
@Controller('cats')
export class CatsController {
constructor(private catsService: CatsService) {}
@Post()
create(@Body('name') name: string): string[] {
return this.catsService.create(name);
}
@Get(':name')
find(@Param('name') name: string): string[] {
return this.catsService.find(name);
}
@Put(':name')
update(@Param('name') from: string, @Body('name') to: string): string[] {
return this.catsService.update(from, to);
}
@Delete(':name')
remove(@Param('name') name: string): string[] {
return this.catsService.remove(name);
}
}
import { Injectable } from '@nestjs/common';
@Injectable()
export class CatsService {
private readonly cats: Array<string> = [];
create(name: string): string[] {
this.cats.push(name);
return this.cats;
}
find(name: string): string[] {
return this.cats.filter(cat => cat === name);
}
update(from: string, to: string): string[] {
const idx = this.cats.indexOf(from);
this.cats[idx] = to;
return this.cats;
}
remove(name: string): string[] {
return this.cats.filter(cat => cat !== name);
}
}
이제 고양이 이름을 받고 출력하는 CRUD를 완료했다.
하지만 고양이는 이름만 가지고 있지 않다, 고양이 이름과 나이, 종류를 추가하여 만들어보자.
그러기 위해선 interface를 만들어야 한다.
인터페이스는 여러개가 생성될 수 있으니 cats 폴더 안 interfaces 폴더를 만들어 넣어주었다.
export interface Cat {
name: string;
age: number;
type: string;
}
또한, 생성 시 Body에 받을 DTO를 만들자.
export class CreateCatDto {
name: string;
age: number;
type: string;
}
이제 Interface와 DTO를 활용하여 서비스와 컨트롤러를 수정해보자!!
데이터 타입은 Array[string] 에서 Array[Cat] 로 바꾸는 작업을 하면 된다.
import { Body, Param, Controller, Delete, Get, Post, Put } from '@nestjs/common';
import { CatsService } from './cats.service';
import { Cat } from './interfaces/cat.interface';
import { CreateCatDto } from './dto/create-cat.dto';
@Controller('cats')
export class CatsController {
constructor(private catsService: CatsService) {}
@Post()
create(@Body() createCatDto: CreateCatDto): Cat[] {
return this.catsService.create(createCatDto);
}
@Get(':name')
find(@Param('name') name: string): Cat[] {
return this.catsService.find(name);
}
@Put(':name')
update(@Param('name') from: string, @Body('name') to: string): Cat[] {
return this.catsService.update(from, to);
}
@Delete(':name')
remove(@Param('name') name: string): Cat[] {
return this.catsService.remove(name);
}
}
import { Injectable } from '@nestjs/common';
import { CreateCatDto } from './dto/create-cat.dto';
import { Cat } from './interfaces/cat.interface';
@Injectable()
export class CatsService {
private readonly cats: Cat[] = [];
create(createCatDto: CreateCatDto): Cat[] {
this.cats.push(createCatDto);
return this.cats;
}
find(name: string): Cat[] {
return this.cats.filter(cat => cat.name === name);
}
update(from: string, to: string): Cat[] {
this.cats.forEach((cat, key) => {
if(cat.name === from) {
cat.name = to;
}
});
return this.cats;
}
remove(name: string): Cat[] {
return this.cats.filter(cat => cat.name !== name);
}
}
끝!
나는 해당 API들을 Postman에서 테스트 해보고 있다.
지금은 고양이들이 Primary Key가 없어서 이름으로 중복되고 삭제 및 수정이 되지만!
우선 CRUD 를 만들어보자는 의미에 의의를 두고!
여기까지 하겠다.
이제 데이터베이스를 연결해 보는 포스트로 돌아오겠다.
'개발 > Nest.js' 카테고리의 다른 글
[Nest.js] Nest.js Basic CRUD 만들기 - 1 (0) | 2023.01.28 |
---|---|
[Nest.js] Nest.js 설치 (0) | 2023.01.28 |