--- tags: Node.js 直播班 - 2022 春季班 --- # 第七週主線任務與講義 * 錄影 * 點名,[報到]() Code:`ima6zTPew9I4` * 每日助教服務上線! * [線上範例程式碼 week7 branch](https://github.com/gonsakon/express-week4-sample) ## imgUr 介接流程 * [教學文件](https://israynotarray.com/nodejs/20220517/432259079/) ## 申請步驟 1. 申請 imgur 服務 2. 建立一個 Album 相簿,並取得 ID 3. 申請 [imgur 應用程式](https://api.imgur.com/oauth2/addclient),獲得 client_id 和 client_secret 4. 申請 refresh token:`https://api.imgur.com/oauth2/authorize?client_id=${Client ID}&response_type=token` ## multer * express 所設計的 middleware * [multer 官方文件](https://github.com/expressjs/multer) * [簡體教學](https://github.com/expressjs/multer/blob/master/doc/README-zh-cn.md) ## 注意細節 * 留意 heroku 記憶體空間,[免費 512 MB](https://devcenter.heroku.com/articles/dyno-types) ## 新增與取消讚 ``` =JavaScript // models/postsModel.js likes: [ { type: mongoose.Schema.ObjectId, ref: 'User' } ] // post router router.post('/:id/likes',isAuth, handleErrorAsync(async function(req, res, next) { const _id = req.params.id; await Post.findOneAndUpdate( { _id}, { $addToSet: { likes: req.user.id } } ); res.status(201).json({ status: 'success', postId: _id, userId: req.user.id }); })); router.delete('/:id/likes',isAuth, handleErrorAsync(async(req, res, next) => { const _id = req.params.id; await Post.findOneAndUpdate( { _id}, { $pull: { likes: req.user.id } } ); res.status(201).json({ status: 'success', postId: _id, userId: req.user.id }); })) ``` ## 按讚列表功能、取得個人貼文列表 * 取得個人貼文列表 ``` =JavaScript router.get('/user/:id', handleErrorAsync(async(req, res, next) => { const user = req.params.id; const posts = await Post.find({user}); res.status(200).json({ status: 'success', results: posts.length, posts }); })) ``` * 取得按讚列表 ``` =JavaScript const Post = require('../models/postsModel'); router.get('/getLikeList',isAuth, handleErrorAsync(async(req, res, next) =>{ const likeList = await Post.find({ likes: { $in: [req.user.id] } }).populate({ path:"user", select:"name _id" }); res.status(200).json({ status: 'success', likeList }); })) ``` ## 第七週主線任務 * [第七週主線任務網址]()