-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmedium-sync.js
More file actions
55 lines (44 loc) · 1.62 KB
/
medium-sync.js
File metadata and controls
55 lines (44 loc) · 1.62 KB
1
2
3
4
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
require('dotenv').config();
const Parser = require('rss-parser');
const { Pool } = require('pg');
const parser = new Parser();
const pool = new Pool({
connectionString: process.env.DB_CONNECTION_STRING,
});
async function fetchAndStoreArticles() {
const feed = await parser.parseURL('https://medium.com/feed/turing-talks');
count = 0;
for (const item of feed.items) {
const mediumId = item.guid;
const summary = item['content:encodedSnippet'].split('\n')[1]?.trim()
const exists = await pool.query('SELECT 1 FROM articles WHERE medium_id = $1', [mediumId]);
if (exists.rows.length === 0) {
try {
await pool.query(
`INSERT INTO articles
(medium_id, title, summary, author, image_url, medium_url, published_at)
VALUES ($1,$2,$3,$4,$5,$6,$7)`,
[
mediumId,
item.title,
summary,
item.creator,
extractImage(item['content:encoded']),
item.link,
item.pubDate
]
);
console.log("Inserido:", item.title);
} catch (err) {
console.error("Erro ao inserir:", err);
}
}
}
console.log('sync concluido');
}
function extractImage(html) {
if (!html) return null;
const match = html.match(/<img.*?src="(.*?)"/);
return match ? match[1] : null;
}
fetchAndStoreArticles().finally(() => pool.end());