Skip to content

Instantly share code, notes, and snippets.

@JeroenVdb
Created August 31, 2015 17:54
Show Gist options
  • Save JeroenVdb/7f87fe87e3b43ca0afdc to your computer and use it in GitHub Desktop.
Save JeroenVdb/7f87fe87e3b43ca0afdc to your computer and use it in GitHub Desktop.
'use strict';
var fs = require('fs'),
url = require('url'),
Promise = require('promise');
module.exports = {
'run': function(entryUrl) {
return new Promise(function(resolve) {
var toAnalyze = {
'entryUrl': entryUrl,
'providers': []
}
getThirdPartyProvidersData(toAnalyze)
.then(findThirdPartyProvider)
.then(returnProv, returnDefaultProv);
});
}
};
function returnProv(provider) {
return new Promise(function(resolve) {
console.log('returnProvider');
resolve(provider);
});
}
function returnDefaultProv(entryUrl) {
return new Promise(function(resolve) {
var returnProvider = {
'id': '',
'name': '',
'matchUrls': [],
'category': 'Unknown',
'entries': [],
'totals': {}
},
urlObject = url.parse(entryUrl);
console.log('return returnDefaultProv');
returnProvider.id = urlObject.host;
returnProvider.name = urlObject.host;
returnProvider.matchUrls.push(urlObject.host);
resolve(returnProvider);
});
}
function getThirdPartyProvidersData(toAnalyze) {
return new Promise(function(resolve) {
var filePath = __dirname + '/data/providers.json';
console.log('getThirdPartyProvidersData');
toAnalyze.providers.push(JSON.parse(fs.readFileSync(filePath, 'utf8')));
resolve(toAnalyze);
});
}
function findThirdPartyProvider(toAnalyze) {
return new Promise(function(resolve, reject) {
var hasMatch = false,
returnProvider;
console.log('findThirdPartyProvider');
toAnalyze.providers.forEach(function(provider) {
if (hasMatchingUrl(provider.matchUrls, toAnalyze.entryUrl)) {
console.log('We did find a match! Good!');
returnProvider = provider;
hasMatch = true;
}
});
console.log('hasmatch; ' + hasMatch);
if (hasMatch) {
resolve(returnProvider);
} else {
reject(toAnalyze.entryUrl);
}
});
}
function hasMatchingUrl(matchUrls, entryUrl) {
var hasMatch = false;
matchUrls.forEach(function(urlRegex) {
var re = new RegExp(urlRegex, 'g'),
result = entryUrl.match(re);
if (result) {
hasMatch = true;
}
});
return hasMatch;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment