1 | import request from 'request';
|
2 | import async from 'async';
|
3 | import { parseString as parseXmlString } from 'xml2js';
|
4 | import isArray from 'lodash.isarray';
|
5 |
|
6 | const parseOptions = {
|
7 | attrkey: 'attributes',
|
8 | charkey: 'label',
|
9 | explicitArray: false,
|
10 | };
|
11 |
|
12 | function doGet(country, page, itemId, callback) {
|
13 | const url = `https://itunes.apple.com/${country}/rss/customerreviews/page=${page}/id=${itemId}/sortBy=mostRecent/xml`;
|
14 |
|
15 | request.get(url, (error, response, body) => {
|
16 | if (!error && response.statusCode === 200) {
|
17 | parseXmlString(body, parseOptions, (err, result) => {
|
18 | const reviews = result.feed.entry || [];
|
19 | if (reviews.length !== 0) {
|
20 | reviews.shift();
|
21 | }
|
22 | callback(null, reviews);
|
23 | });
|
24 | } else {
|
25 | callback(error);
|
26 | }
|
27 | });
|
28 | }
|
29 |
|
30 | function getByCountry(country, pageCount, itemId, callback) {
|
31 | function asyncSuccess(n, next) {
|
32 | const num = n + 1;
|
33 |
|
34 | doGet(country, num, itemId, (err, data) => {
|
35 | next(err, data);
|
36 | });
|
37 | }
|
38 |
|
39 | function asyncFail(err, result) {
|
40 | if (err) {
|
41 | callback(err);
|
42 | } else {
|
43 | let concatenated = [];
|
44 |
|
45 | result.forEach((chunk) => {
|
46 | concatenated = concatenated.concat(chunk);
|
47 | });
|
48 |
|
49 | callback(null, concatenated);
|
50 | }
|
51 | }
|
52 |
|
53 | async.times(pageCount, asyncSuccess, asyncFail);
|
54 | }
|
55 |
|
56 | function getReviews(countries, pageCount, itemId, callback) {
|
57 | let result = [];
|
58 | const countriesArr = isArray(countries) ? countries : [countries];
|
59 |
|
60 | function asyncSuccess(country, next) {
|
61 | getByCountry(country, pageCount, itemId, (error, data) => {
|
62 | if (!error) {
|
63 | if (data.length === 0) {
|
64 | next();
|
65 | } else {
|
66 | result[country] = data;
|
67 | next();
|
68 | }
|
69 | } else {
|
70 | next(error);
|
71 | }
|
72 | });
|
73 | }
|
74 |
|
75 | function asyncFail(err) {
|
76 | if (err) {
|
77 | console.log(err);
|
78 | }
|
79 |
|
80 | callback(null, result);
|
81 | }
|
82 |
|
83 | async.each(countriesArr, asyncSuccess, asyncFail);
|
84 | }
|
85 |
|
86 | module.exports = getReviews;
|