openclient
Version:
An opinionated client for RESTful APIs (particularly OpenStack's).
64 lines (54 loc) • 1.78 kB
JavaScript
module.exports = {
urljoin: function () {
// Constructs URLs with proper slashes regardless of leading/trailing
// slashes on the arguments passed in.
var url = "";
for (var i = 0, j = arguments.length; i < j; i++) {
var arg = arguments[i];
if (typeof(arg) === "undefined") {
continue;
}
arg = arg.toString();
// Strip any preceding slashes since we append slashes to everything.
if (arg.substr(0, 1) === "/") {
arg = arg.substr(1);
}
// Add a trailing slash unless this is the end of URL.
if (arg.substr(-1) !== "/" && i !== arguments.length - 1) {
arg += "/";
}
// Join the current piece to our URL string.
url += arg;
}
return url;
},
interpolate: function (string, mapping) {
return string.replace(/\{([^{}]*)\}/g, function (pattern, lookup) {
var replacement = mapping[lookup];
return (typeof replacement === 'string' || typeof replacement === 'number') ? replacement : pattern;
});
},
is_ans1_token: function (token) {
// Credit goes to Adam Young for figuring this out. See Keystone's
// source code for the logic/math that proves it.
return token.indexOf("MII") === 0 ? true : false;
},
/**
* For each `key`, `val` in each of `obj...`, set `target[key]` = `val` if `target[key]` is undefined
*/
defaults: function(target /*, obj...*/) {
var args = Array.prototype.slice.call(arguments, 0),
current, key, val;
args.shift();
current = args.shift();
while(current) {
for (key in current) {
if (typeof target[key] === "undefined") {
target[key] = current[key];
}
}
current = args.shift();
}
return target;
}
};