forked from simontegg/promises
-
Notifications
You must be signed in to change notification settings - Fork 2
/
nested-with-postgres.js
73 lines (51 loc) · 1.67 KB
/
nested-with-postgres.js
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import Promise from 'bluebird'
import fs from 'fs'
import pg from 'pg'
import request from 'superagent'
import cheerio from 'cheerio'
import Url from 'url'
import R from 'ramda'
const connectionString = process.env.DATABASE_URL || "postgres://localhost:5432/spider"
const handleError = (err) => {
console.log('Oh no! An error:', err)
}
const extractUrls = R.compose(
R.uniq,
R.filter(href => R.match(/http/g, href).length > 0),
R.map(anchor => anchor.attribs.href),
R.filter(anchor => anchor.attribs && anchor.attribs.href),
R.values
)
const db = new pg.Client(connectionString)
db.connect(err => {
if (err) { handleError(err) }
db.query('SELECT url FROM websites', (err, result) => {
R.forEach((url) => {
let hostname = Url.parse(url).hostname
request
.get(url)
.end((err, res) => {
if (err) { handleError(err) }
let $ = cheerio.load(res.text)
let links = R.filter(u => {
let urlObj = Url.parse(u)
return urlObj.hostname !== hostname
}, extractUrls($('a')))
let data = { links: links }
console.log(url)
db.query(`UPDATE websites SET data=$1 WHERE url=$2`, [data, url], (err, result) => {
if (err) { handleError(err) }
console.log('insert result', result, url)
// console.log('result', result)
db.query('SELECT * FROM websites', (err, result) => {
if (err) { handleError(err) }
result.rows.forEach(row => {
console.log('row', row)
})
db.end()
})
})
})
}, R.map(row => row.url, result.rows))
})
})