Skip to content

Instantly share code, notes, and snippets.

@joepie91
Last active August 29, 2015 14:23
Show Gist options
  • Save joepie91/cee42198b6bc6a24ea44 to your computer and use it in GitHub Desktop.
Save joepie91/cee42198b6bc6a24ea44 to your computer and use it in GitHub Desktop.
External image cacheing
var Promise = require("bluebird");
var bhttp = require("bhttp");
var currentImage;
function fetchNewImage(){
var fetchPromise = Promise.try(function(){
/* You can replace this with anything that returns a promise, really... */
return bhttp.get("http://remote-site.com/image.jpg");
}).then(function(response){
/* We just want the body, which is the image data as a Buffer... */
return response.body;
});
if (currentImage == null) {
/* First time we're fetching the image, set the promise immediately. */
currentImage = fetchPromise;
} else {
/* Not the first time; we only update the currentImage value once we're done fetching it. */
fetchPromise.then(function(image){
currentImage = fetchPromise;
})
}
setTimeout(fetchNewImage, 10 * 60 * 1000); // every 10 minutes
}
fetchNewImage(); // fetch it the first time
/* Actually using the image: */
app.get("/image", function(req, res){
currentImage.then(function(image){ // this will only run once we *have* an image
res.set("Content-Type", "image/png"); // or whatever content-type is appropriate for the image
res.send(image);
})
})
/* Possible scenarios here:
* 1) Image fetched for the first time, not done yet; the /image route will wait for completion.
* 2) Image fetched for the first time, done; the .then in the /image route triggers immediately.
* 3) Image fetched for the Nth time, not done yet; currentImage still has the old image, and triggers immediately.
* 4) Image fetched for the Nth time, done; currentImage is replaced with the new image we completed fetching just now.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment