var request = require('request'); /** * ## Responses * Responses from this API with be wrapped in an envelope to assist the caller * in dealing with the various responses from the service. There are no types * to check against in JavaScript, so this facilitates that. * * { * status: 200, * data: { name: "John", age: 29 } * } * * ## Logging * To enable logging, use the NODE_DEBUG environment variable. * * NODE_DEBUG=apidoc * * @constructor */ function Storebackapi (host) { var showLogMessages = process.env.NODE_DEBUG ? process.env.NODE_DEBUG.indexOf('apidoc') !== -1 : false; function log (message) { if (showLogMessages) { console.log('[apidoc] ' + message); } } function getQueryString (options) { var params = []; var qs = options.qs || {}; for (var key in qs) { if (qs[key]) { params.push(key + '=' + qs[key]); } } return params.join('&'); } function doRequest (options) { var startMs = Date.now(); options = options || {}; if (!options.json) { options.json = true; } options.qsStringifyOptions = { arrayFormat: 'repeat' }; var queryString = getQueryString(options); var url = options.uri + (queryString ? '?' + queryString : ''); log(options.method + ' ' + url); if (options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH') { log('|--> With body:\n\t\t' + JSON.stringify(options.json)); } return new Promise(function (resolve, reject) { request(options, function (err, response) { if (err) { reject(err); return; } var duration = Date.now() - startMs; var requestHref = response.request ? response.request.href : ''; log('Completed ' + options.method + ' ' + requestHref + ' ' + response.statusCode + ' ' + duration + 'ms'); resolve(response); }); }); } /** * Simple plain object check. This is actually really involved to be 100% * accurate */ function isObject (obj) { return typeof obj === 'object' && !Array.isArray(obj); } var Products = (function Products() { /** * Returns a product by ID or by handle. The following API will return a product object sanitized of private information from shopify. It should be thought of as a serializer or alturnative interface to the public shopify information per a product. * * @param {string} productId */ function getProductsByProductId(productId) { var url = host + '/v1/products/' + productId + ''; var queryString = { }; var requestOpts = { qs: queryString, uri: url, method: 'GET' }; return doRequest(requestOpts).then(function (serverResponse) { switch (serverResponse.statusCode) { case 200: return Promise.resolve(serverResponse.body); case 400: return Promise.reject({ status: serverResponse.statusCode, data: serverResponse.body }); case 404: return Promise.reject({ status: serverResponse.statusCode, data: serverResponse.body }); default: return Promise.reject(new Error('Unknown response code: ' + serverResponse.statusCode)); } }); } return { getProductsByProductId: getProductsByProductId, }; }()); this.Products = Products; } module.exports = Storebackapi;