nest generate service
movies.service.ts 파일이 생성되었다.
Service에는 보통 비즈니스 로직을 삽입한다.
Controller 에서 정의했던 getAll(), create(), deleteOne() 같은 함수들을 Service에서 정의하는 것이다.
니코쌤은 일단 Fake DB 를 쓴다고 한다. (메모리 상에서 돌아가는 디비 말하는 것)
DB를 쓰려면 먼저 Entity를 정의한다.
데이터베이스와 데이터를 주고받을 때 사용할 데이터 필드를 담은 틀 이라고 생각하면 된다.
import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateMovieDto } from './dto/create-movie.dto';
import { Movie } from './entities/movie.entity';
@Injectable()
export class MoviesService {
private movies: Movie[] = [];
getAll(): Movie[] {
return this.movies;
}
// id를 받아와서 id값에 만족하는 첫번째 요소의 값을 반환함.
getOne(id: string): Movie {
const movie = this.movies.find((movie) => movie.id === +id);
if (!movie) {
throw new NotFoundException(`Movie with ID ${id} not found. `);
}
return movie;
}
// filter 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환한다.
deleteOne(id: string) {
this.getOne(id);
// 매개변수로 받은 id를 제외시키고 필터링시킨다.
this.movies = this.movies.filter((movie) => movie.id !== +id);
}
create(movieData: CreateMovieDto) {
this.movies.push({
id: this.movies.length + 1,
...movieData,
});
}
update(id: string, updateData) {
const movie = this.getOne(id);
this.deleteOne(id);
this.movies.push({ ...movie, ...updateData });
}
}
지금은 임시 데이터베이스 (가장 상단에 있는 Movie[])를 사용했다.
저 리스트에 접근하면서 데이터를 주고 받고한다. 추후에 저 Movie[]를 데이터베이스로 교체하면 될 것 같다.
Service 정의를 완료했다면 다시 Controller로 돌아가서 Service에 있는 메서드를 쓰도록 해주면 된다.
import {...};
@Controller('movies')
export class MoviesController {
// 가져올 때 이렇게만 써주면 서비스를 쓸 수 있다....
constructor(private readonly moviesService: MoviesService) {}
@Get()
getAll(): Movie[] {
return this.moviesService.getAll();
}
@Get('/:id')
getOne(@Param('id') id: string): Movie {
return this.moviesService.getOne(id);
}
@Post()
create(@Body() movieData) {
return this.moviesService.create(movieData);
}
// 데이터를 지울 때 Delete 요청을 사용한다.
@Delete('/:id')
remove(@Param('id') movieId: string) {
// return `This will delete a movie id : ${movieId}`;
return this.moviesService.deleteOne(movieId);
}
// 리소스의 일부를 업데이트 해줄때는 Patch 를 쓴다
@Patch('/:id')
path(@Param('id') moiveId: string, @Body() updateData) {
return {
updatedMovie: moiveId,
...updateData,
};
}
}
... 그러면 Service에 선언된 리스트를 통해서 어느정도 데베를 흉내낼 수 있게 된다.