Thu Jul 28 2016
Copied to clipboard! Copy reply
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
"use strict";

module.exports = function(v){
    
	var https = require('https');
	
	if(!v){
		return Promise.reject('Must be called with an object to normalize');
	}
	
	function resolveEntry(e){
		if(!e.id){
			return Promise.reject('Entry must have ID');
		}
		var endpoint = `https://cdn.contentful.com/spaces/celb27rot2s1/entries/${e.id}?access_token=701ff15332e0d10fb95c4032ea5a81afd8563b98e487c1188f53f390f5d6495d`;
		var p = new Promise(function(resolve, reject){
			var req = https.request(endpoint, function(res,err){
					!!err && reject('API Endpoint Request Failed: ' + endpoint);
					var body = '';
					res.on('data', function(chunk){ body += chunk; });
					res.on('end', function(){
						console.log('API Endpoint returned: ' + endpoint);
						try {
							var resultJSON = JSON.parse(body);
							if('fields' in resultJSON){
								resolve(resultJSON.fields);
							}
							else {
								reject('JSON from entry endpoint ' + e.id + ' did not have "fields" as expected.');
							}
						}
						catch(e) {
							reject('Response did not parse to JSON as expected from provided endpoint: ' + endpoint);
						}
					});
				});
				req.end();
		});
		
		return p;
	}
	
	return Promise.all([resolveEntry(v.fields.promo[0].sys), resolveEntry(v.fields.crescendo[0].sys), Promise.resolve(v.fields.name)]);
	
}