Skip to content

Instantly share code, notes, and snippets.

@bign8
Created May 27, 2014 04:14
Show Gist options
  • Save bign8/6f4d012b654acbe4d492 to your computer and use it in GitHub Desktop.
Save bign8/6f4d012b654acbe4d492 to your computer and use it in GitHub Desktop.
Gravatar Proxy with Node.js
var app = require('express')(),
gravatar_proxy = require('./gravatar-proxy.js');
app.all('/gravatar/:hash', gravatar_proxy()); // http://localhost/gravatar/example@example.com
var http = require('http'),
crypto = require('crypto'),
fs = require('fs'),
sep = require('path').sep
proxy_base = __dirname + sep + 'gravatar-proxy' + sep,
known_bad = [];
// Gravatar Docs: https://en.gravatar.com/site/implement/images/
module.exports = function(basePath, apiKey) {
var proxyTo = function(url, response, cache_file, hash) {
try {
return http.get(url, function (res) {
if (res.statusCode == 200) {
var writable = fs.createWriteStream( cache_file );
res.pipe( writable );
res.pipe( response );
} else {
response.sendfile(proxy_base + 'none.jpg');
known_bad.push(hash);
}
});
} catch (err) {
response.writeHead(500, { "Content-Type": "text/html" });
response.end(url, err.message);
}
};
var proxy = function(req, res) {
var hash = crypto.createHash('md5').update( req.params.hash ).digest('hex'),
cache_file = proxy_base + hash + '.jpg';
return fs.exists( cache_file, function (exists) {
if ( exists ) {
res.sendfile( cache_file );
} else if ( known_bad.indexOf(hash) > -1 ) {
res.sendfile(proxy_base + 'none.jpg');
} else {
proxyTo('http://gravatar.com/avatar/'+hash+'?d=404&s=100', res, cache_file, hash);
}
});
};
return proxy;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment