Skip to content

Instantly share code, notes, and snippets.

@macalinao
Created July 31, 2016 20:48
Show Gist options
  • Save macalinao/dc4fd1334cf2a3c46dab365fcd132d9b to your computer and use it in GitHub Desktop.
Save macalinao/dc4fd1334cf2a3c46dab365fcd132d9b to your computer and use it in GitHub Desktop.
var _ = require('lodash');
var P = require('bluebird');
var apac = require('apac');
var OperationHelper = apac.OperationHelper;
var opHelper = new OperationHelper({
awsId: process.env.AMAZON_AWS_ID,
awsSecret: process.env.AMAZON_AWS_SECRET,
assocId: process.env.AMAZON_SITE_ID
});
function search(term, page) {
var itemSearch = P.promisify(opHelper.execute, opHelper);
return itemSearch('ItemSearch', {
SearchIndex: 'Books',
Keywords: term,
ResponseGroup: 'Small,ItemAttributes,Images,EditorialReview,OfferSummary',
ItemPage: page || 1
}).then(function(results) {
console.log(results);
function v(item) {
return (item || [])[0];
}
function o(item) {
return item || {};
}
results = o(v(o(o(v(results)).ItemSearchResponse).Items)).Item;
return _.map(results, function(item) {
var a = o(v(item.ItemAttributes));
var offer = o(v(item.OfferSummary));
var ret = {
image: v(o(v(o(item.LargeImage))).URL),
title: v(a.Title),
manufacturer: v(a.Manufacturer),
author: v(a.Author),
isbn: v(a.ISBN),
buyback: v(o(v(a.TradeInValue)).FormattedPrice),
newPrice: v(o(v(offer.LowestNewPrice)).FormattedPrice),
usedPrice: v(o(v(offer.LowestUsedPrice)).FormattedPrice),
list: v(o(v(a.ListPrice)).FormattedPrice),
desc: v(o(v(o(v(item.EditorialReviews)).EditorialReview)).Content),
url: v(item.DetailPageURL),
slug: require('slug')(v(a.Title))
};
return ret;
});
});
}
/**
* Search the amazon API with 3 retries.
*/
function searchWithRetry(term, page, tries) {
if (typeof tries === 'undefined') tries = 3;
if (tries === 0) {
return P.resolve([]);
}
return search(term, page).then(function(results) {
if (results.length === 0) {
return searchWithRetry(term, page, tries - 1);
}
return results;
});
}
module.exports = searchWithRetry;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment