Skip to content

Instantly share code, notes, and snippets.

@chtzvt
Last active September 12, 2016 04:15
Show Gist options
  • Save chtzvt/f8879b103384f9592ab6c86a1421cee5 to your computer and use it in GitHub Desktop.
Save chtzvt/f8879b103384f9592ab6c86a1421cee5 to your computer and use it in GitHub Desktop.
Proxies Imgur links through Google Cloud Functions
var request = require('request');
var IMGUR_API_KEY = '<your key here>';
exports.fetchImage = function fetchImage(req, res) {
if (req.path === undefined || req.path.length <= 1) {
res.status(400).send('{"error":"No Data"}');
return;
}
var params = {
url: 'https://api.imgur.com/3/image/' + req.path,
headers: {
"Authorization": 'Client-ID ' + IMGUR_API_KEY
}
};
request.get(params, function(err, response, data) {
if (err) {
res.status(500).send('{"error":"Couldn\'t connect to Imgur"}');
throw new Error("Failed to read Imgur API response: " + JSON.parse(err));
}
var img = JSON.parse(response.body);
if (typeof img.data.link === 'undefined' || img.data.link.indexOf('http') === -1)
res.status(500).send('{"error":"API error or image not found"}');
console.log("Fetched " + img.data.link.replace(/\\/g, ""));
request
.get(img.data.link.replace(/\\/g, ""))
.pipe(res, {
end: true
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment