-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
70 lines (58 loc) · 2.57 KB
/
index.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
var request = require('request'),
cheerio = require('cheerio'),
fields = require('./lib/fields'),
utils = require('./lib/utils');
var Item = function () {};
Item.prototype.setProp = function(key, value) {
this[key] = value;
};
var getOpenGraph = function(options, callback) {
var cb = callback || utils.createPromiseCallback();
request(options, function(err, response, body) {
if(!err && response.statusCode === 200) {
var $ = cheerio.load(body),
title = $('head title'),
meta = $('head').find('meta[property*="og:"], meta[property*="fb:"], meta[property*="twitter:"]'),
openGraph = {};
meta.each(function(idx) {
var key = $(this).attr('property');
var value = $(this).attr('content');
var data = fields[key];
var groupItem;
if (!data) return;
if (!data.group) {
openGraph[data.fieldName] = value;
} else if (data.type === 'item') {
openGraph[data.group] = new Item();
openGraph[data.group].setProp(data.fieldName, value);
} else if (data.type === 'array') {
if (Array.isArray(openGraph[data.group])) {
groupItem = openGraph[data.group][openGraph[data.group].length - 1];
} else {
groupItem = openGraph[data.group];
}
groupItem = openGraph[data.group] || {};
groupItem[data.fieldName] = openGraph[data.group][data.fieldName] || [];
groupItem[data.fieldName].push(value);
} else {
if (Array.isArray(openGraph[data.group])) {
groupItem = openGraph[data.group][openGraph[data.group].length - 1];
} else if (data.type === 'arrayItem' || !groupItem) {
groupItem = new Item();
openGraph[data.group] = openGraph[data.group] || [];
openGraph[data.group].push(groupItem);
}
groupItem.setProp(data.fieldName, value);
}
});
if (!openGraph.title) {
openGraph.title = title.text();
}
cb(null, openGraph);
} else {
cb(err);
}
});
return cb.promise;
};
module.exports = getOpenGraph;