Last active
September 12, 2016 04:15
-
-
Save chtzvt/f8879b103384f9592ab6c86a1421cee5 to your computer and use it in GitHub Desktop.
Proxies Imgur links through Google Cloud Functions
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 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