review.controller.js 2.09 KB
Newer Older
1
2
import Review from '../models/Review.js'
import cheerio from "cheerio";
Kim, Chaerin's avatar
서연    
Kim, Chaerin committed
3
import axios from 'axios';
4

Kim, Chaerin's avatar
Kim, Chaerin committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const search = async (req, res, next) => {
    let DuplicateCheckReview = []
    if (!req.body.db) { DuplicateCheckReview = await Review.find({ keyword: req.query.keyword }) }
    if (!req.body.db && DuplicateCheckReview !== []) {
        req.review = DuplicateCheckReview
    } else {
        try {
            let reviews = []
            let url = "https://www.google.com/search?q=" + encodeURI(req.query.keyword) + `+site%3Atistory.com&start=${Number(req.query.index) * 10}`
            console.log(url)
            let response1 = await axios.get(url)
            let $1 = cheerio.load(response1.data);
            $1('.kCrYT').each(async function (i) {
                let title = $1(this).find('h3').text()
                let searchParams = new URLSearchParams($1(this).find('a').attr('href'));
                let link = searchParams.get("/url?q")
                let summary = $1(this).find('.s3v9rd').find('.s3v9rd').text()
                if (title) {
                    reviews[i] = { title: title, link: link, keyword: [req.query.keyword] }
                } else if (summary) {
                    reviews[i - 1] = { ...reviews[i - 1], summary: summary }
                    reviews = reviews.filter(e => e)
                }
            })
            req.review = reviews
        } catch (error) {
            console.log("6")
            console.log(error)
        }
34
    }
Kim, Chaerin's avatar
Kim, Chaerin committed
35
    next()
36
37
}

Kim, Chaerin's avatar
Kim, Chaerin committed
38
39
40
41
42
43
44
45
46
const save = async (req, res) => {
    req.review.forEach(async (reviews, i) => {
        const review = await Review.findOne({ link: reviews.link })
        if (review) {
            await Review.updateOne({ link: reviews.link }, { $push: { bookmark: req.query.keyword } })
            req.review[i] = ""
        }
        else {
            await new Review(reviews).save()
Kim, Chaerin's avatar
Kim, Chaerin committed
47
48
        }
    })
Kim, Chaerin's avatar
Kim, Chaerin committed
49
50
51
52
    console.log(req.review.length)
    req.review = req.review.filter(e => e)
    console.log(req.review.length)
    res.status(200).send({ review: req.review, db: true, index: Number(req.query.index) + 1 })
53
}
Kim, Chaerin's avatar
Kim, Chaerin committed
54
export default { search, save }