Skip to content

Instantly share code, notes, and snippets.

@tdieterich-bb
Last active August 29, 2015 14:09
Show Gist options
  • Save tdieterich-bb/48f2e36dbc795ed0da3b to your computer and use it in GitHub Desktop.
Save tdieterich-bb/48f2e36dbc795ed0da3b to your computer and use it in GitHub Desktop.
NodeJS compatible example that allows a search for a product by keyword, and provide product availability in stores near the zip code and radius.
/*jslint node:true*/
'use strict';
var _ = require('lodash'),
bluebird = require('bluebird'),
request = bluebird.promisifyAll(require('request')),
baseUrl = 'http://api.remix.bestbuy.com',
compiled = _.template('(search=${searchTerm})+stores(area(${zipCode},${radius}))'),
defaults = {
searchTerm: 'ipad',
zipCode: '55423',
radius: 25
};
function buildAvailabilityParams(options) {
options.page = options.page === undefined ? 1 : options.page;
return {
url: baseUrl + '/v1/products' + compiled({
searchTerm: options.searchTerm,
zipCode: options.zipCode,
radius: options.radius
}),
qs: {
format: 'json',
show: 'sku,name,stores',
sort: 'bestSellingRank.asc',
page: options.page,
apiKey: process.env.API_KEY
},
json: true
};
}
function logResults(results) {
_.each(results, function(product) {
console.log('\n' + product.name + ' (sku: ' + product.sku + ') is availabile at:');
console.log(_.times(product.name.length + product.sku.toString().length + 26, function(n) { return '-'; }).join(''));
console.log(_.map(product.stores, function(store) { return ' ' + store.name + ' (#' + store.storeId + ')'; }).join('\n'));
});
}
function getProductAvailability(options) {
_.defaults(options, defaults);
return request.getAsync(buildAvailabilityParams(options)).spread(function (resp, page1) {
if (resp.statusCode !== 200) {
return bluebird.reject(new Error('Response Status Code: ' + resp.statusCode));
}
var totalPages = page1.totalPages;
return bluebird.map(_.range(2, totalPages + 1), function (page) {
options.page = page;
return request.getAsync(buildAvailabilityParams(options)).spread(function (resp, pageN) {
return pageN.products;
});
}, {
concurrency: 10 // we have found this adequate for our default API key QPS throttling (5 QPS)
}).then(function (results) {
results.unshift(page1.products);
return results;
});
}).then(function (results) {
results = _.flatten(results);
logResults(results);
return results;
}).catch(function (error) {
console.log(error);
});
}
// Example Usage:
getProductAvailability({ searchTerm: 'DSLR', zipCode: '55419', radius: '15' });
// Expanding the search radius out too far may result in 504 errors due to the size/complexity of the query:
// getProductAvailability({ searchTerm: 'DSLR', zipCode: '55419', radius: '1000' });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment