-
Notifications
You must be signed in to change notification settings - Fork 1
/
camel-client.js
77 lines (65 loc) · 2.14 KB
/
camel-client.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
74
75
76
77
const URL = require('url');
const axios = require('axios');
const cheerio = require('cheerio');
const matchingHosts = [/\bamazon\.com$/i, /\ba\.co$/i]
module.exports = class CamelClient {
static isAmazonUrl(url) {
try {
const parsed = URL.parse(url);
return matchingHosts.some(match => parsed.hostname.match(match));
} catch (e) {
return false;
}
}
static async getCamelInfo(post) {
const url = post.url;
const result = await axios.get(`https://camelcamelcamel.com/search?sq=${encodeURIComponent(url)}`);
if (result.status !== 200) {
return null;
}
try {
const page = cheerio.load(result.data);
const amazonSection = page('#section_amazon');
if (!amazonSection.length) {
return null;
}
const thirdPartySection = page('#section_new');
const amazonPrice = this.getSectionPrice(amazonSection);
const thirdPartyNewPrice = this.getSectionPrice(thirdPartySection);
if (!amazonPrice.lowest && !thirdPartyNewPrice.lowest) {
return null;
}
return {
post,
amazon: amazonPrice,
thirdPartyNew: thirdPartyNewPrice,
url: `https://camelcamelcamel.com${result.request.path}`,
};
} catch (e) {
console.error(`Unable to parse ${url} due to ${e.message}`);
console.error(e);
}
return null;
}
static getSectionPrice(section) {
if (!section.length) {
return null;
}
const highest = section.find('.highest_price'),
lowest = section.find('.lowest_price');
return {
highest: this.getCellValue(highest),
lowest: this.getCellValue(lowest),
};
}
static getCellValue(parentCell) {
if (!parentCell.length) {
return null;
}
const cells = parentCell.find('td');
return {
price: cells.eq(1).text(),
date: cells.eq(2).text(),
};
}
}