Skip to content

Instantly share code, notes, and snippets.

@jsiesquen
Created December 18, 2018 22:07
Show Gist options
  • Save jsiesquen/d9c044045075bfb2bf1c07bcad109d70 to your computer and use it in GitHub Desktop.
Save jsiesquen/d9c044045075bfb2bf1c07bcad109d70 to your computer and use it in GitHub Desktop.
Sample code using request-promise on nodeJs
const rp = require('request-promise');
const rq = require('request');
require('dotenv').config();
let endpointFeed = `https://domain.com/feed/orders/status?limit=10`;
let endpointOrderSeller = `https://domain.com/orders/`;
let requestConfiguration = {
method: 'GET',
json: true,
resolveWithFullResponse: false,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/vnd.vtex.ds.v10+json',
'X-VTEX-API-AppKey': `xxxxxxxxxxxxxxxx`,
'X-VTEX-API-AppToken': `xxxxxxxxxxxxxxxxxxxxxxxx`
}
};
let noValidOrders = [];
let validOrders = [];
exports.handler = function(event, context) {
/* Get Orders Feed */
rp(endpointFeed, requestConfiguration)
.then((response) => {
if (response.length) {
response.forEach(element => {
if (['payment-completed']
.findIndex(value => value == element.status) >= 0) {
validOrders.push({
id: element.orderId,
status: element.status,
commitToken: element.commitToken
});
}
else {
noValidOrders.push({
id: element.orderId,
status: element.status,
commitToken: element.commitToken
});
}
});
}
return validOrders;
})
.then(async (orders) => {
getOrderDetails(orders);
})
.catch((handleError) => {
console.log("[Get Orders Feed: Error]: ", handleError.StatusCodeError, handleError.StatusCodeError);
throw handleError;
});
};
/* Get Order's Product Code */
let getOrderDetails= (orders) => {
let promises = [];
orders.forEach(function(order) {
requestConfiguration.url = endpointOrderSeller + order.id;
requestConfiguration.resolveWithFullResponse = true;
var promise = new Promise((resolve, reject) => {
rq(requestConfiguration, (error, response, body) => {
if (body.error === undefined) {
let products = body.items;
if (products !== undefined) {
let result = { product: [],
orderPurchaseDate: body.creationDate,
orderId: body.marketplaceOrderId
};
products.forEach(function(item, index, array) {
result .product.push({item: item.id, productName: item.name});
});
if (result.product.length)
return resolve(result);
else
return reject();
}
}
});
});
promises.push(promise);
});
Promise.all(promises)
.then((productCodes) => {
console.log('[GET Products Code]:', productCodes);
console.log(productCodes); // Final result
})
.catch((error) => {
console.log('[GET Products Code: Error]:', error);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment