Created
April 1, 2015 09:31
-
-
Save MarkySparky/b58744be209d1b7b6e79 to your computer and use it in GitHub Desktop.
Content Source - fetches published content and notifies a ContentHandler of each published item.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Content Source - fetches published content and notifies a ContentHandler of each published item. | |
**/ | |
module.exports = function (config, sessionId, contentFormatter, contentHandler) { | |
var restler = require('restler'); | |
var async = require('async'); | |
var authHeader = { | |
headers : { | |
'Authorization': 'Bearer ' + sessionId | |
} | |
}; | |
// return a url for this item (if empty then will return the url for all items) | |
function url(id) { | |
return config.buildapi.endpoint + 'items/' + id; | |
} | |
// fetch the item with this id | |
function fetchItem(id, callback) { | |
var itemUrl = url(id); | |
restler | |
.get(itemUrl, authHeader) | |
.on("complete", function(data, response) { | |
if (data instanceof Error || response.statusCode !== 200) { | |
callback(data); | |
} else { | |
try { | |
var contentItem = contentFormatter.format(JSON.parse(data)); | |
contentHandler.handleContentItem(contentItem, | |
function () { | |
callback(null, contentItem); | |
}); | |
} catch (error) { | |
callback(error); | |
} | |
} | |
}); | |
} | |
// fetch all published ID's then fetch each item in turn | |
function fetchIDs() { | |
var publishedIDsURL = url(''); | |
restler.get(publishedIDsURL, authHeader) | |
.on('complete', function(data, response) { | |
if (data instanceof Error || response.statusCode !== 200) { | |
contentHandler.end(data); | |
} else { | |
try { | |
var ids = JSON.parse(data); | |
//Limit the pull to 50 items whilst testing | |
ids = ids.slice(1,20); | |
async.each(ids,fetchItem, | |
function(err) { | |
contentHandler.end(err); | |
}); | |
} catch (error) { | |
contentHandler.end(error); | |
} | |
} | |
}); | |
} | |
return { | |
getContent: function () { | |
// tell the content Handler we are starting so that it can perform | |
contentHandler.start( | |
function () { | |
// start by fetching the bublished id's | |
fetchIDs(); | |
}); | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment