Skip to content

Instantly share code, notes, and snippets.

@roboncode
Last active August 29, 2015 14:07
Show Gist options
  • Save roboncode/1de7d0766c5711b80d6c to your computer and use it in GitHub Desktop.
Save roboncode/1de7d0766c5711b80d6c to your computer and use it in GitHub Desktop.
Provides instructions from an API based on simple rules and converts it to Mongo instructions for setting object in database
var JsonUtil = (function (exports) {
exports = exports || {};
var reserved = 'userId name'.split(' ');
var dates = 'updateLastRequestOn'.split(' ');
var incs = 'newSession'.split(' ');
var e;
var isObject;
function fixUpdate(string) {
string = string.substr(6);
return string.charAt(0).toLowerCase() + string.slice(1);
}
for (e in reserved) {
reserved[reserved[e]] = true;
}
for (e in dates) {
dates[dates[e]] = true;
}
for (e in incs) {
incs[incs[e]] = true;
}
var toMongo = function (data) {
var result = { customAttributes: {} };
var $inc = data.increments;
delete data.increments;
var $remove = {};
var o = {
customAttributes: data.customAttributes || {}
};
for (var n in data) {
if (dates[n]) {
n = fixUpdate(n);
result[n] = Date.now();
} else if (incs[n]) {
if (!result.$inc) {
result.$inc = {};
}
result.$inc[n] = 1;
} else if (reserved[n]) {
result[n] = data[n];
} else {
isObject = typeof data[n] === 'object';
if (!isObject) {
if(data[n] === '$remove') {
$remove[n] = '';
} else {
o.customAttributes[n] = data[n];
}
}
}
}
// flatten the customAttributes so not to override any
flatten(o, {}, result);
if ($inc) {
result.customAttributes.$inc = $inc;
}
result.$unset = $remove;
return result;
};
var flatten = function (source, opts, target) {
opts = opts || {};
var delimiter = opts.delimiter || '.';
target = target || {};
function step(object, prev) {
Object.keys(object).forEach(function (key) {
var value = object[key];
var isarray = opts.safe && Array.isArray(value);
var type = Object.prototype.toString.call(value);
var isobject = (
type === '[object Object]' ||
type === '[object Array]'
);
var newKey = prev ? prev + delimiter + key : key;
if (!isarray && isobject) {
return step(value, newKey);
}
target[newKey] = value;
});
}
step(source);
return target;
};
exports.toMongo = toMongo;
exports.flatten = flatten;
return exports;
})();
var data = {
userId: 1,
name: 'John Smith',
email: 'john@mycompany.com',
updateLastRequestOn: true,
newSession: true,
noLongerNeeded: '$remove',
increments: {
firstCount: 1,
secondCount: -2
},
bogus: {
name: 'Nobody'
}
};
var mongoData = JsonUtil.toMongo(data);
JSON.stringify(mongoData);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment