Created
May 27, 2014 04:14
-
-
Save bign8/6f4d012b654acbe4d492 to your computer and use it in GitHub Desktop.
Gravatar Proxy with Node.js
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
var app = require('express')(), | |
gravatar_proxy = require('./gravatar-proxy.js'); | |
app.all('/gravatar/:hash', gravatar_proxy()); // http://localhost/gravatar/example@example.com | |
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
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