freeCodeCamp/server/utils/index.js

108 lines
2.6 KiB
JavaScript
Raw Normal View History

2015-08-24 23:19:06 +00:00
var cheerio = require('cheerio'),
2015-06-04 00:14:45 +00:00
request = require('request'),
2015-06-19 21:32:17 +00:00
MDNlinks = require('../../seed/bonfireMDNlinks'),
2015-06-04 00:14:45 +00:00
resources = require('./resources.json'),
nonprofits = require('../../seed/nonprofits.json');
/**
* Cached values
*/
2015-08-24 23:19:06 +00:00
var allNonprofitNames;
module.exports = {
2015-06-23 00:24:55 +00:00
dasherize: function dasherize(name) {
return ('' + name)
.toLowerCase()
.replace(/\s/g, '-')
.replace(/[^a-z0-9\-\.]/gi, '');
},
unDasherize: function unDasherize(name) {
return ('' + name)
// replace dash with space
.replace(/\-/g, ' ')
// strip nonalphanumarics chars except whitespace
.replace(/[^a-zA-Z\d\s]/g, '')
.trim();
2015-06-23 00:24:55 +00:00
},
randomPhrase: function() {
return resources.phrases[
Math.floor(Math.random() * resources.phrases.length)
];
},
randomVerb: function() {
return resources.verbs[
Math.floor(Math.random() * resources.verbs.length)
];
},
randomCompliment: function() {
return resources.compliments[
Math.floor(Math.random() * resources.compliments.length)
];
},
allNonprofitNames: function() {
if (allNonprofitNames) {
return allNonprofitNames;
} else {
allNonprofitNames = nonprofits.map(function(elem) {
return {name: elem.name};
});
return allNonprofitNames;
}
},
whichEnvironment: function() {
return process.env.NODE_ENV;
},
2015-06-25 22:03:46 +00:00
getURLTitle: function(url, callback) {
var result = {
title: '',
image: '',
url: '',
description: ''
};
request(url, function(err, response, body) {
if (err || response.statusCode !== 200) {
return callback(new Error('failed'));
}
var $ = cheerio.load(body);
var metaDescription = $("meta[name='description']");
var metaImage = $("meta[property='og:image']");
var urlImage = metaImage.attr('content') ?
metaImage.attr('content') :
'';
var metaTitle = $('title');
var description = metaDescription.attr('content') ?
metaDescription.attr('content') :
'';
result.title = metaTitle.text().length < 90 ?
metaTitle.text() :
metaTitle.text().slice(0, 87) + '...';
result.image = urlImage;
result.description = description;
callback(null, result);
});
2015-06-19 21:32:17 +00:00
},
getMDNLinks: function(links) {
if (!links) {
return [];
}
// takes in an array of links, which are strings
// for each key value, push the corresponding link
// from the MDNlinks object into a new array
return links.map(function(value) {
return MDNlinks[value];
});
}
};