From b883e87b1e5222388e6562296009a49126d3af3c Mon Sep 17 00:00:00 2001 From: Trygve Laugstøl Date: Thu, 28 Jun 2012 12:27:39 +0200 Subject: o Initial import of application/vnd.collection+json parser code. --- index.js | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 index.js (limited to 'index.js') diff --git a/index.js b/index.js new file mode 100644 index 0000000..5705fec --- /dev/null +++ b/index.js @@ -0,0 +1,40 @@ +var _ = require('underscore'); + +/** + * Takes any object and make it look like a collection+json object with utility methods. + */ +function fromObject(root) { + root = root || {}; + var collection = root.collection || {}; + collection.items = collection.items || {}; + collection.links = collection.links || {}; + collection.queries = collection.queries || {}; + collection.templates = collection.templates || {}; + + collection.mapItemData = function(f) { + return _.map(collection.items, function(item) { +// console.log("item", item); + var map = _.reduce(item.data, function(map, field) { +// console.log("field", field); + map[field.name] = field.value; + return map; + }, {}); +// console.log("map", map); + return f(map); + }); + }; + + return collection; +} +module.exports.fromObject = fromObject; + +function fromString(s) { + var object = {}; + try { + object = JSON.parse(s); + } + catch(ex) { + } + return fromObject(object); +} +module.exports.fromString = fromString; -- cgit v1.2.3