|
| 1 | +const axios=require('axios'); |
| 2 | +const cheerio=require('cheerio'); |
| 3 | +const { Model, Op } = require('sequelize'); |
| 4 | +const { CompanyNews, Company } = require('../models/DB'); |
| 5 | +const fetchNews = require('../utils/NaverStockNews'); |
| 6 | + |
| 7 | +async function fetchNewsContent(link) { |
| 8 | + try { |
| 9 | + const response = await axios.get(link); |
| 10 | + const $ = cheerio.load(response.data); |
| 11 | + const content = |
| 12 | + $("#newsct_article").text().trim() || |
| 13 | + $("._article_content").text().trim(); |
| 14 | + return content; |
| 15 | + } catch (error) { |
| 16 | + console.error(`Error fetching news content from ${link}:`, error); |
| 17 | + return null; |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +async function saveCodes() { |
| 22 | + const companies = await Company.findAll(); |
| 23 | + const companyCodes = companies.map((company) => ({ |
| 24 | + code: company.dataValues.code, |
| 25 | + id: company.dataValues.id, |
| 26 | + })); |
| 27 | + return companyCodes; |
| 28 | +} |
| 29 | +function delay(ms) { |
| 30 | + return new Promise((resolve) => setTimeout(resolve, ms)); |
| 31 | +} |
| 32 | +async function saveNewsToDatabase(id, newsItems) { |
| 33 | + const newsData = []; |
| 34 | + |
| 35 | + //console.log("newsItems", newsItems); |
| 36 | + for (let items of newsItems) { |
| 37 | + for (let item of items) { |
| 38 | + const link = `https://n.news.naver.com/article/${item.officeId}/${item.articleId}`; |
| 39 | + |
| 40 | + // 1초 지연 (1000ms) |
| 41 | + await delay(100); |
| 42 | + |
| 43 | + try { |
| 44 | + const detailedContent = await fetchNewsContent(link); |
| 45 | + |
| 46 | + newsData.push({ |
| 47 | + title: item.title, |
| 48 | + content: detailedContent || item.body, |
| 49 | + link: link, |
| 50 | + company_id: id, |
| 51 | + }); |
| 52 | + } catch (error) { |
| 53 | + console.error(`Error fetching news content for ${link}:`, error); |
| 54 | + // 에러 처리 (예: 특정 뉴스 아이템에 대한 실패를 로그로 남기거나, 다시 시도할 수 있도록 로직 추가) |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + // 데이터베이스에 저장 |
| 59 | + if (newsData.length > 0) { |
| 60 | + await CompanyNews.bulkCreate(newsData); |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +// Express 컨트롤러 함수 |
| 65 | +async function handleNewsDatas(data, res) { |
| 66 | + try { |
| 67 | + // fetchNews 함수로 뉴스 아이템들 가져오기 |
| 68 | + const newsItems = await fetchNews(data.code); |
| 69 | + |
| 70 | + // 가져온 뉴스 아이템들을 데이터베이스에 저장하기 |
| 71 | + await saveNewsToDatabase(data.id, newsItems); |
| 72 | + } catch (error) { |
| 73 | + console.error(`Error handling news data for company ${data.id}:`, error); |
| 74 | + // 에러 처리 (예: 특정 회사에 대한 실패를 로그로 남기거나, 다시 시도할 수 있도록 로직 추가) |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +const handleCompanyNews = async (req, res, next) => { |
| 79 | + try { |
| 80 | + // 회사 코드를 데이터베이스에서 가져오기 |
| 81 | + const companyCodes = await saveCodes(); |
| 82 | + |
| 83 | + // 각 회사 코드에 대해 뉴스 아이템을 가져오고 데이터베이스에 저장하기 |
| 84 | + for (const data of companyCodes) { |
| 85 | + await handleNewsDatas(data, res); |
| 86 | + } |
| 87 | + |
| 88 | + res |
| 89 | + .status(200) |
| 90 | + .json({ message: `Successfully fetched and saved news items.` }); |
| 91 | + } catch (error) { |
| 92 | + console.error("Error handling news data:", error); |
| 93 | + // 에러 응답 보내기 |
| 94 | + res.status(500).json({ error: "Failed to fetch and save news items." }); |
| 95 | + } |
| 96 | +}; |
| 97 | + |
| 98 | +module.exports = handleCompanyNews; |
0 commit comments