node-express로 REST API 만들기(3)

Seungsoo Lee·2022년 8월 25일
0

web

목록 보기
8/13

앞선 포스트에서
1. 설치
2. mongo db 연결
3. port 열기
4. route 설정
5. DB Schema 설정
6. Auth(register, login) api
7. Users api
이 과정을 다 해주었다.

이제 마지막으로 Posts api를 완성시켜보겠다.
8. Posts api

Posts API

  • user에 관한 API는 어느정도 완성이 되었다. 실제 서비스 부분인 글 쓰는 부분을 api로 작성해야하는데, 이를 ./server/routes/posts.js 에다가 써보기로 한다.

create a post
update a post
delete a post
like or dislike a post
get a post
get timeline posts

- create a post

  • Post를 생성해보려고 한다. 따라서 post method를 사용하였다.
  • 먼저 새 post를 생성하기 위해 const newPost = new Post(req.body) 를 사용한다.
  • const savedPost = await newPost.save() 를 통해 mongo db에 저장을 해준다.
// create a post
router.post("/", async (req, res) => {
	const newPost = new Post(req.body);
	try {
		const savedPost = await newPost.save();
		res.status(200).json(savedPost);
	} catch (err) {
		res.status(500).json(err);
	}
});

- update a post

  • post를 업데이트를 해주기 위해 post = await Post.findById(req.param.id) 을 사용해서 업데이트 해줄 post를 변수에 지정해준다.
  • await post.updateOne({ $set: req.body }) 를 통해 req.body의 내용을 업데이트해준다.
// update a post
router.put("/:id", async (req, res) => {
	try {
		const post = await Post.findById(req.params.id);
		if (post.userId === req.body.userId) {
			await post.updateOne({ $set: req.body });
			res.status(200).json("the post has been updated");
		} else {
			res.status(403).json("you can update only your post");
		}
	} catch (err) {
		res.status(500).json(err);
	}
	
});

- delete a post

  • post를 삭제 해주기 위해 delete method를 사용해줄것이다.
  • 먼저 const post = await Post.findById(req.params.id); 로 findById를 통해 post를 찾아준다.
  • await post.deleteOne({ $set: req.body }); 그 선택한 post를 deleteOne으로 삭제시킨다.
// delete a post
router.delete("/:id", async (req, res) => {
	try {
		const post = await Post.findById(req.params.id);
		if (post.userId === req.body.userId) {
			await post.deleteOne({ $set: req.body });
			res.status(200).json("the post has been delete");
		} else {
			res.status(403).json("you can delete only your post");
		}
	} catch (err) {
		res.status(500).json(err);
	}
	
})

- like or dislike a post

  • post를 like 하거나 dislike하는 기능을 추가하기 위해서 put method로 api를 만들어보았다.
  • const post = await Post.findById(req.params.id); 원하는 post를 찾아준다.
  • 만약 like 주체가 post의 like array에 없다면 await post.updateOne({ $push: { likes: req.body.userId } }); 로 like array를 업데이트 해준다.
  • 만약 like 주체가 이미 post의 like array에 있다면, await post.updateOne({ $pull: { likes: req.body.userId } }); 로 like array를 업데이트 해준다.
// like or dislike a post
router.put("/:id/like", async (req, res) => {
	try {
		const post = await Post.findById(req.params.id);
		if(!post.likes.includes(req.body.userId)) {
			await post.updateOne({ $push: { likes: req.body.userId } });
			res.status(200).json("The post has been liked");
		} else {
			await post.updateOne({ $pull: { likes: req.body.userId } });
			res.status(200).json("The post has been disliked");
		}
	} catch (err) {
		res.status(500).json(err);
	}
	
})

- get a post

  • const post = await Post.findById(req.params.id); 를 통해 원하는 post를 받아온다.
  • res.status(200).json(post); 로 post 정보를 response해준다.
// get a post
router.get("/:id", async (req, res) => {
	try {
		const post = await Post.findById(req.params.id);
		res.status(200).json(post);
	} catch (err) {
		res.status(500).json(err);
	}
})

- get timeline posts

  • timeline에 post들을 보여주기 위한 api가 필요하다. 조건은 (내가 팔로우 하는 사람 + 내) 포스트를 보여줄것이다.
  • 그러기위해서 일단 자신의 포스트를 const userPosts = await Post.find({ userId: currentUser._id }); 로 가져와주고,
  • const friendPosts = await Promise.all(
    			currentUser.followings.map((friendId) => {
    				return Post.find({ userId: friendId });
    			})
    		);
    로 자신이 following하는 friend를 find해주고 그것을 friendPosts에 넣어준다.
  • res.json(userPosts.concat(...friendPosts)); 를 통해 userPost에다가 frienPost를 더해주고 response를 해준다. 이러면 모든 following하고 더해서 내 포스트 까지 전달이 될 것 이다.
// get timeline posts
router.get("/timeline/all", async (req, res) => {
	try {
		const currentUser = await User.findById(req.body.userId);
		const userPosts = await Post.find({ userId: currentUser._id });
		const friendPosts = await Promise.all(
			currentUser.followings.map((friendId) => {
				return Post.find({ userId: friendId });
			})
		);
		res.json(userPosts.concat(...friendPosts));
	} catch (err) {
		res.status(500).json(err);
	}
})

0개의 댓글