모든 레포지토리의 함수는 async, 비동기이다.
Find -> 특정 조건에 맞는 데이터를 다 가져온다.
async getAllPosts() {
return this.postsRepository.find(조건);
}
FindOne -> 하나의 데이터만 찾기
전처럼 파라미터 id를 입력해주고 이에 맞게 조건이 id: id인 데이터만 찾아오도록 했다.
async getPostById(id: number) {
const post = await this.postsRepository.findOne({
where: {
id: id,
},
});
if (!post) {
throw new NotFoundException();
}
return post
}
create를 사용할 때의 방향
1) create -> 저장할 객체를 생성한다.
2) save -> 객체를 저장한다. (create 메서드에서 생성한 객체로)
async createPost(author: string, title: string, content: string) {
// 1) create -> 저장할 객체를 생성한다.
// 2) save -> 객체를 저장한다. (create 메서드에서 생성한 객체로)
const post = this.postsRepository.create({
author,
title,
content,
likeCount: 0,
commentCount: 0,
});
const newPost = await this.postsRepository.save(post);
return newPost;
}
save의 기능
id 기준
1. 만약에 데이터가 존재하지 않는다면 새로 생성한다.
2. 만약에 데이터가 존재한다면 업데이트한다.
async updatePost(
postId: number,
author: string,
title: string,
content: string,
) {
const post = await this.postsRepository.findOne({
where: {
id: postId,
},
});
if (!post) {
throw new NotFoundException();
}
if (author) {
post.author = author;
}
if (title) {
post.title = title;
}
if (content) {
post.content = content;
}
const newPost = await this.postsRepository.save(post);
return newPost;
}
delete -> 게시물 삭제
async deletePost(postId: number) {
const post = await this.postsRepository.findOne({
where: {
id: postId,
}
});
if (!post) {
throw new NotFoundException();
}
await this.postsRepository.delete(postId);
return postId;
}
}