This repository has been archived by the owner on Mar 22, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
65 lines (51 loc) · 1.45 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
'use strict';
var xml2js = require('xml2js');
var parseFeedSync = function (feed, options) {
var obj;
xml2js.parseString(feed, options, function (error, data) {
if (error) {
throw error;
}
if (!data.rss) {
error = new Error('The root element is not `rss`');
} else if (!data.rss.channel) {
error = new Error('There is no `channel` element');
} else if (data.rss.channel.length !== 1) {
error = new Error('There is more than one `channel` element');
} else if (!data.rss.channel[0].item) {
error = new Error('There is no `item` element');
}
if (error) {
throw error;
}
obj = data;
});
return obj;
};
var mergeItems = function (items, feeds, options) {
feeds.forEach(function (f) {
items = items.concat(parseFeedSync(f, options).rss.channel[0].item);
});
return items.sort(function (a, b) {
return new Date(a.pubDate).getTime() - new Date(b.pubDate).getTime();
}).reverse();
};
exports.merge = function (feeds, options) {
var channel;
var feed;
if (!options) {
options = {};
}
options.explicitArray = true;
feed = parseFeedSync(feeds.shift(), options);
channel = feed.rss.channel[0];
channel.item = mergeItems(channel.item, feeds, options);
channel.lastBuildDate = channel.item[0].pubDate;
return feed;
};
exports.stringify = function (feed, options) {
if (!options) {
options = {};
}
return new xml2js.Builder(options).buildObject(feed);
};