フォロー機能いいね機能をmongoDB + mongooseで作成
今回はAPIの作成で難しかった尚且つあまり詳細な情報がなかった。
フォロー機能のといいね機能をmongoDB + mongooseで作成していきます
まずはユーザーのフォローとフォローの解除から
//ユーザーのフォロー
users.put("/:id/follow", async ( req:express.Request,res:express.Response ) => {
if ( req.body.userId !== req.params.id ) {
try {
//params.id = 自分ではないユーザー
const user = await User.findById(req.params.id);
const currentUser = await User.findById(req.body.userId);
//フォロワーに自分がいなかったら、TRUEになりフォローできる
if ( !user?.followers.includes(req.body.userId)) {
await user?.updateOne({
$push: {
followers: req.body.userId,
},
});
await currentUser?.updateOne({
$push: {
followings: req.params.id
},
});
return res.status(200).json("フォローに成功しました");
} else {
return res.status(403).json("すでにフォローしています");
}
} catch (error) {
res.status(500).json(error);
}
} else {
res.status(500).json("フォローできません")
}
});
//フォローの解除
users.put("/:id/unfollow", async ( req:express.Request,res:express.Response ) => {
if ( req.body.userId !== req.params.id ) {
try {
//params.id = 自分ではないユーザー
const user = await User.findById(req.params.id);
const currentUser = await User.findById(req.body.userId);
//フォロワーに自分が存在したら、フォローを解除する
if ( user?.followers.includes(req.body.userId)) {
await user?.updateOne({
$pull: {
followers: req.body.userId,
},
});
await currentUser?.updateOne({
$pull: {
followings: req.params.id
},
});
return res.status(200).json("フォローを解除しました");
} else {
return res.status(403).json("すでにフォローを解除しています");
}
} catch (error) {
res.status(500).json(error);
}
} else {
res.status(500).json("フォロー解除できません")
}
});
フォローする
1・まず自分をフォローはできないので、自分ではないことを条件に、考える
2・次にフォローされる側のフォロワーにincludes(req.body.userId)関数を使って
自分がいないことを条件にmongooseのupdateOne({$push: {プロパティ: 値 },
関数を使ってフォローする側のidを格納しアップデートする
3・2と同じ要領でフォローした側の方にフォローされた側のidを格納しアップデートする
フォローを解除する
こちらは逆のことをすればいい
注意したいのは$pushで格納ではなく、$pullで取り除くことが必要
あとはフォローするときと違って、自分がいることを条件にするのを忘れないように
いいね機能
//特定の投稿にいいねをする
posts.put("/:id/like", async (req:express.Request,res:express.Response) => {
try {
const post = await Post.findById(req.params.id);
//自分がいいねしていなかったら、TRUEになりフォローできる
if ( !post?.likes.includes(req.body.userId)) {
await post?.updateOne({
$push : {
likes: req.body.userId,
},
});
return res.status(200).json("いいねしました")
} else {
await post?.updateOne({
$pull : {
likes: req.body.userId,
},
});
return res.status(403).json("すでにいいねしています");
};
} catch (error) {
res.status(403).json(error);
}
})
いいね機能
これもフォローの時と似たような考えだが、いいねの場合は自分自身もフォローできる仕様にした
かったので、自分ではないことを条件にするのは無くした。
あとはほぼ一緒
今回はmongoDBで実装したが、この考え方さえ覚えれば、mySQLでもいけるかな。
次はmySQLでも挑戦しようと思う