Last active
October 24, 2020 18:40
-
-
Save RyanKor/670f694487043d5555c167f1b2926eff to your computer and use it in GitHub Desktop.
Hash Tag Controller/post.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Post, Hashtag } = require("../models"); | |
exports.textUpload = async (req, res, next) => { | |
try { | |
const post = await Post.create({ | |
content: req.body.content, | |
img: req.body.url, | |
userId: req.user.id, | |
}); | |
const hashtags = req.body.content.match(/#[^\s#]*/g); | |
if (hashtags) { | |
const result = await Promise.all( | |
hashtags.map((tag) => | |
Hashtag.findOrCreate({ | |
where: { title: tag.slice(1).toLowerCase() }, | |
}) | |
) | |
); | |
await post.addHashtags(result.map((ans) => ans[0])); | |
} | |
res.redirect("/"); | |
} catch (error) { | |
console.error(error); | |
next(error); | |
} | |
}; | |
exports.hashtagSearch = async (req, res, next) => { | |
const query = req.query.hashtag; | |
if (!query) { | |
return res.redirect("/"); | |
} | |
try { | |
const hashtag = await Hashtag.findOne({ where: { title: query } }); | |
let contents = []; | |
if (hashtag) { | |
contents = await hashtag.getPosts({ include: [{ model: User }] }); | |
} | |
return res.render("main", { | |
title: `${query} | SNS Clone`, | |
user: req.user, | |
contents: contents, | |
}); | |
} catch (error) { | |
console.error(error); | |
return next(error); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment