review.controller.js 1.93 KB
Newer Older
1
import Review from '../models/Review.js'
Kim, Chaerin's avatar
Kim, Chaerin committed
2
import cheerio, { html } from "cheerio";
3
4
5
import jschardet from 'jschardet'
import iconv from 'iconv'
import fs from 'fs'
Kim, Chaerin's avatar
서연    
Kim, Chaerin committed
6
import axios from 'axios';
Kim, Chaerin's avatar
Kim, Chaerin committed
7
import { nextTick } from 'process';
8
9
const Iconv = iconv.Iconv

Kim, Chaerin's avatar
Kim, Chaerin committed
10
11
12
const search = async (req, res, next) => {
    try {
        let reviews = []
13
14
        let content = []
        const url = "https://www.google.com/search?q=" + encodeURI(req.params.search) + "+site%3Atistory.com&page_no=1"
Kim, Chaerin's avatar
Kim, Chaerin committed
15
        const response1 = await axios.get(url)
16
        // console.log(response1.data)
Kim, Chaerin's avatar
Kim, Chaerin committed
17
18
19
        const $1 = cheerio.load(response1.data);
        $1('.kCrYT').each(async function (i) {
            const title = $1(this).find('h3').text()
20
            const searchParams = new URLSearchParams($1(this).find('a').attr('href'));
Kim, Chaerin's avatar
Kim, Chaerin committed
21
22
            const link = searchParams.get("/url?q")
            const summary = $1(this).find('.s3v9rd').find('.s3v9rd').text()
Kim, Chaerin's avatar
상준    
Kim, Chaerin committed
23
            content.push(getReview(link))
Kim, Chaerin's avatar
Kim, Chaerin committed
24
            if (title) {
25
                reviews[i] = { title: title, link: link }
Kim, Chaerin's avatar
Kim, Chaerin committed
26
27
28
29
            } else if (summary) {
                reviews[i - 1] = { ...reviews[i - 1], summary: summary }
                reviews = reviews.filter(e => e)
            }
30
        })
31
32
33
        let promiseReview = await Promise.all(content)
        promiseReview = promiseReview.filter(e => typeof (e) === 'string')
        reviews.forEach(async (review, i) => {
34
35
            review["content"] = promiseReview[i]
        })
Kim, Chaerin's avatar
Kim, Chaerin committed
36
37
38
39
        res.send(reviews)
    } catch (error) {
        console.log(error)
        res.send(error)
40
41
42
    }
}

Kim, Chaerin's avatar
상준    
Kim, Chaerin committed
43
const getReview = async (link) => {
44
    if (link) {
45
        let content = '없음'
46
47
48
49
50
        const res = await axios.get(link)
        const $2 = cheerio.load(res.data);
        if ($2('.tt_article_useless_p_margin').text()) {
            content = $2('.tt_article_useless_p_margin').text()
        }
51
52
        return content
        console.log(content, link)
Kim, Chaerin's avatar
Kim, Chaerin committed
53
54
    }
}
Kim, Chaerin's avatar
?    
Kim, Chaerin committed
55

Kim, Chaerin's avatar
Kim, Chaerin committed
56
export default { search, getReview }