Skip to content

Instantly share code, notes, and snippets.

@carloseberhardt
Last active August 29, 2015 13:56
Show Gist options
  • Save carloseberhardt/8947749 to your computer and use it in GitHub Desktop.
Save carloseberhardt/8947749 to your computer and use it in GitHub Desktop.
Javascript callout for the Apigee Edge platform. This script will convert JSON attribute names to camelCase from hyphen-case or underscore_case and vice versa. Work remains to be done on the inbound flow.
function convertProps(obj, propNameConverterFn) {
var r, p, thing, i, L, what = Object.prototype.toString, wo = what.call(obj);
if (wo == "[object Object]") {
r = {};
for (p in obj) {
if (obj.hasOwnProperty(p)) {
thing = obj[p];
if (what.call(thing) == "[object Object]" || what.call(thing) == "[object Array]") {
r[propNameConverterFn(p)] = convertProps(thing, propNameConverterFn);
}
else {
r[propNameConverterFn(p)] = thing;
}
}
}
}
else if (wo == "[object Array]") {
r = [];
for (i=0, L=obj.length; i<L; ++i ) {
thing = obj[i];
if (what.call(thing) == "[object Object]" || what.call(thing) == "[object Array]") {
r[i] = convertProps(thing, propNameConverterFn);
}
else {
r[i] = thing;
}
}
}
else {
var msg = "Unknown object to covert: " + wo + "("+ JSON.stringify(obj, null, 2).slice(0, 34) +")";
console.log(msg);
throw {error: true, message: msg };
}
return r;
}
function propsToCamel(obj) {
return convertProps(obj, toCamel);
}
function propsToDash(obj) {
return convertProps(obj, toDash);
}
function propsToHyphen(obj) {
return convertProps(obj, toHyphen);
}
function toCamel(str) {
return str.replace(/([-_][a-z])/g, function($1){return $1.toUpperCase().replace(/[-_]/,'');});
}
function toDash(str) {
return str.replace(/([A-Z])/g, function($1){return "-"+$1.toLowerCase();});
}
function toHyphen(str) {
return str.replace(/([A-Z])/g, function($1){return "_"+toLowerCase();});
}
/* ====================================================== */
var obj, converted;
//debug
print("Flow: " + context.flow);
switch(context.flow) {
case "PROXY_REQ_FLOW":
// check if we're handling POST or PUT and convert accordingly
break;
case "PROXY_RESP_FLOW":
// convert to camelCase
obj = JSON.parse(response.content);
converted = propsToCamel(obj);
response.content = JSON.stringify(converted, null, 2);
break;
case "TARGET_REQ_FLOW":
// alternate spot to handle POST or PUT - depends on other flow logic
break;
case "TARGET_RESP_FLOW":
// alternate spot to handle converting to camelCase - depends on other flow logic
break;
default:
// do nothing
break;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment