mozu-node-sdk
Version:
Mozu JavaScript SDK for Node.js and Arc.js environments
80 lines (70 loc) • 2.66 kB
JavaScript
;
const extend = require('./tiny-extend');
const request = require('./request');
module.exports = function(config) {
function doRequest(body, options) {
options = options || {};
let finalRequestConfig = extend({}, config, this.defaultRequestOptions, {
url: this.urlResolver(this, config.url, body),
context: this.context,
body: body
}, options);
let 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) {
let 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(
(p, t) => p.then(t),
Promise.resolve({
client: this,
options: options,
requestConfig: config
})
).then(doThisRequest);
}
};
};