Untitled
unknown
plain_text
10 months ago
3.4 kB
6
Indexable
const db = require('../../../models/index') const getPostContent = (req, res) => { const userID = req.user_id const postID = req.query.post_id const findPostPromise = (postID) => { return db.post.findOne({ attributes: { exclude: [ "createdAt", "updatedAt", "deletedAt" ] }, where: { id: postID, }, include: [ { model: db.tag, through: { attributes: [] }, attributes: ["id", "category", "text"], }, { model: db.postpicture, attributes: ["id", "name"], } ] }) .then(postInst => { if (postInst === null) throw new Error("Cannot find any post by post_id") return postInst }) .catch(err => { throw new Error("[Fail to find the post]: " + err) }) } const updatePostClickPromise = (postInst, t) => { return postInst.increment('user_clicked_count', { by: 1 }, { transaction: t }) .then(() => { return postInst }) .catch(err => { throw new Error("[Fail to update post click count]: " + err) }) } const createUserClickOnPostPromise = (userID, postID, t) => { return db.data_user_clicks_on_post.create({ user_id: userID, post_id: postID }, { transaction: t }) .catch(err => { throw new Error("[Fail to create user click on post]: " + err) }) } const collectUserClickOnPostPromise = (postInst, userID, postID, t) => { return db.data_user_clicks_on_post.findOne({ where: { user_id: userID, post_id: postID } }) .then(postClickInst => { if (postClickInst !== null) return postClickInst.increment('click_count', { by: 1 }, { transaction: t }) else return createUserClickOnPostPromise(userID, postID, t) }) .then(() => { return postInst }) .catch(err => { throw new Error("[Fail to update user clicks on post count]: " + err) }) } const postPostProcessing = (postInst) => { postInst.postpictures.forEach(picture => { picture.dataValues.picture = process.env.AWS_CLOUDFRONT_URL + picture.dataValues.name delete picture.dataValues.name }) postInst.dataValues.pictures = postInst.dataValues.postpictures delete postInst.dataValues.postpictures return postInst } const checkPostStatus = (start, end) => { const currentDate = new Date() currentDate.setHours(currentDate.getHours() - 8); if (start <= currentDate && currentDate <= end) return "進行中" else if (currentDate < start) return "即將進行" else return "已結束" } return db.sequelize.transaction((t) => { return findPostPromise(postID) .then(postInst => { return updatePostClickPromise(postInst, t) }) .then(postInst => { return collectUserClickOnPostPromise(postInst, userID, postID, t) }) .then(postInst => { return postPostProcessing(postInst) }) .then(postInst => { postInst.dataValues.status = checkPostStatus(postInst.start_date, postInst.end_date) return postInst }) .then(postInst => { return res.status(200).send(postInst) }) .catch(err => { return res.status(400).send(err.message) }) }) } module.exports = getPostContent
Editor is loading...
Leave a Comment