UNPKG

mozu-node-sdk

Version:

Mozu JavaScript SDK for Node.js and Arc.js environments

67 lines (60 loc) 2.58 kB
'use strict'; var extend = require('./tiny-extend'); var request = require('./request'); module.exports = function (config) { function doRequest(body, options) { options = options || {}; var finalRequestConfig = extend({}, config, this.defaultRequestOptions, { url: this.urlResolver(this, config.url, body), context: this.context, body: body }, options); var finalMethod = finalRequestConfig.method && finalRequestConfig.method.toUpperCase(); // this is magic and was never a good idea. // the way the SDK was designed, the first argument to a method will get // used both as the request payload and as an object to expand the URI // template. this resulted in collisions, and in unexpected behavior with // services that didn't expect strongly typed payloads. the below code // tried to fix it magically, but under certain circumstances it would be // very hard to debug. // // remove any properties from the body that were used to expand the url // if (body && // typeof body === "object" && // !Array.isArray(body) && // !options.body && // !options.includeUrlVariablesInPostBody && // (finalMethod === "POST" || finalMethod === "PUT")) { // finalRequestConfig.body = Object.keys(body).reduce(function(m, k) { // if (!urlSpec.keysUsed[k]) { // m[k] = body[k]; // } // return m; // }, {}); // if (Object.keys(finalRequestConfig.body).length === 0) { // delete finalRequestConfig.body; // } // } if (finalMethod === "GET" || finalMethod === "DELETE" && !options.body) { delete finalRequestConfig.body; // it's outlived its usefulness, we've already made a url with it } return request(finalRequestConfig, this.requestTransform); } return function (body, options) { var doThisRequest = doRequest.bind(this, body, options); if (process.env.mozuHosted) { return doThisRequest(); } else if (!this.prerequisiteTasks || !Array.isArray(this.prerequisiteTasks)) { return Promise.reject(new Error('Could not place request. No `prerequisiteTasks` array found on ' + 'the client object. To require no auth or URL prerequisites, set ' + '`this.prerequisiteTasks = [];` on the client object.')); } else { return this.prerequisiteTasks.reduce(function (p, t) { return p.then(t); }, Promise.resolve({ client: this, options: options, requestConfig: config })).then(doThisRequest); } }; };