|
| 1 | +require("dotenv").config(); |
| 2 | +const blogRouter = require("express").Router(); |
| 3 | +const Blog = require("../models/blog"); |
| 4 | +const User = require("../models/user"); |
| 5 | +const Comment = require("../models/comment"); |
| 6 | +const jwt = require("jsonwebtoken"); |
| 7 | +const { tokenExtractor } = require("../utils/middleware"); |
| 8 | + |
| 9 | +blogRouter |
| 10 | + .route("/") |
| 11 | + .get(async (req, res) => { |
| 12 | + const blogs = await Blog.find({}).populate("user").populate("comments"); |
| 13 | + res.json(blogs); |
| 14 | + }) |
| 15 | + .post(tokenExtractor, async (req, res) => { |
| 16 | + const { author, title, url, likes } = req.body; |
| 17 | + |
| 18 | + const user = await User.findById(req.user); |
| 19 | + |
| 20 | + if (!title || !url) res.status(400).end(); |
| 21 | + |
| 22 | + const blog = new Blog({ |
| 23 | + author: author || "unknown", |
| 24 | + title, |
| 25 | + url, |
| 26 | + likes: likes || 0, |
| 27 | + user: user._id, |
| 28 | + }); |
| 29 | + |
| 30 | + const savedBlog = await blog.save(); |
| 31 | + user.blogs = [...user.blogs, savedBlog._id]; |
| 32 | + await user.save(); |
| 33 | + res.status(201).json(savedBlog); |
| 34 | + }); |
| 35 | + |
| 36 | +blogRouter |
| 37 | + .route("/:id") |
| 38 | + .get(async (req, res) => { |
| 39 | + const blog = await Blog.findById(req.params.id); |
| 40 | + if (blog) { |
| 41 | + res.json(blog.toJSON()); |
| 42 | + } else { |
| 43 | + res.status(404).end(); |
| 44 | + } |
| 45 | + }) |
| 46 | + .delete(tokenExtractor, async (req, res) => { |
| 47 | + const { user } = req; |
| 48 | + const blog = await Blog.findById(req.params.id); |
| 49 | + |
| 50 | + if (blog === null) return res.status(400).end(); |
| 51 | + |
| 52 | + if (blog.user.toString() === user) { |
| 53 | + await Blog.findByIdAndRemove(req.params.id); |
| 54 | + res.status(204).end(); |
| 55 | + } else { |
| 56 | + res.status(400).end(); |
| 57 | + } |
| 58 | + }) |
| 59 | + .put(async (req, res) => { |
| 60 | + const { comments, ...blog } = req.body; |
| 61 | + const updatedBlog = await Blog.findByIdAndUpdate(req.params.id, blog, { |
| 62 | + new: true, |
| 63 | + }); |
| 64 | + res.json(updatedBlog); |
| 65 | + }); |
| 66 | + |
| 67 | +blogRouter.route("/:id/comments").post(async (req, res) => { |
| 68 | + const blogId = req.params.id; |
| 69 | + const content = req.body.comment; |
| 70 | + |
| 71 | + const blog = await Blog.findById(blogId); |
| 72 | + |
| 73 | + if (!content) res.status(400).end(); |
| 74 | + |
| 75 | + const comment = new Comment({ |
| 76 | + content, |
| 77 | + blog: blogId, |
| 78 | + }); |
| 79 | + |
| 80 | + const savedComment = await comment.save(); |
| 81 | + blog.comments = [...blog.comments, comment._id]; |
| 82 | + await blog.save(); |
| 83 | + res.status(201).json(savedComment); |
| 84 | +}); |
| 85 | + |
| 86 | +module.exports = blogRouter; |
0 commit comments