var http = require('http');
var url = require('url');

var renderPng = function (req, res) {
  var options = url.parse(renderPng.getScreenshotPath(req));
  http.get(options, function (screenshot) {
    res.status(screenshot.statusCode);
    for (var i in screenshot.headers) {
      res.setHeader(i, screenshot.headers[i]);
    }
    screenshot.pipe(res);
  }).on('error', function (e) {
    res.status(500);
    res.send('Got error: ' + e.message);
  });
};

if (global.config) {
  renderPng.screenshotServiceUrl = config.screenshotServiceUrl;
  renderPng.screenshotTargetUrl = config.screenshotTargetUrl;
}

renderPng.getScreenshotPath = function (req) {
  var url = req.url;
  var selector = req.query.selector || '.visualisation-inner figure';
  return [
    renderPng.screenshotServiceUrl,
    '?readyExpression=!!document.querySelector(".loaded")',
    '&forwardCacheHeaders=true',
    '&clipSelector=' + selector,
    '&url=',
    renderPng.screenshotTargetUrl,
    url.replace(/.png/g, '')
  ].join('');
};

module.exports = renderPng;

@@ -58,184 +58,493 @@
 r re
-nderPng = function (req, res) %7B%0A  var options = url.parse(renderPng.getScreenshotPath(req));%0A  http.get(options, function (screenshot) %7B%0A    res.status(screenshot.statusCode);%0A
+quirejs = require('requirejs');%0A%0Avar ErrorController = require('./server/controllers/error');%0Avar Model = requirejs('extensions/models/model');%0Avar PageConfig = requirejs('page_config');%0A%0Avar renderPng = function (req, res) %7B%0A  var options = url.parse(renderPng.getScreenshotPath(req));%0A  http.get(options, function (screenshot) %7B%0A    if (screenshot.statusCode %3E 399) %7B%0A      return renderError(screenshot.statusCode, req, res);%0A    %7D else %7B%0A      res.status(screenshot.statusCode);%0A  
     
@@ -575,24 +575,26 @@
 .headers) %7B%0A
+  
       res.se
@@ -632,18 +632,22 @@
 %5D);%0A    
+ 
+ 
 %7D%0A
+  
     scre
@@ -664,16 +664,22 @@
 e(res);%0A
+    %7D%0A
   %7D).on(
@@ -697,17 +697,16 @@
 nction (
-e
 ) %7B%0A    
@@ -711,67 +711,318 @@
   re
-s.status(500);%0A    res.send('Got error: ' + e.message);%0A  %7D
+nderError(500, req, res);%0A  %7D);%0A%7D;%0A%0Avar renderError = function (status, req, res) %7B%0A  var model = new Model(%7B%0A    status: status %7C%7C 500%0A  %7D);%0A  model.set(PageConfig.commonConfig(req));%0A  var error = new ErrorController(%7B%0A    model: model%0A  %7D);%0A  error.render();%0A  res.statusCode = status;%0A  res.send(error.html
 );%0A%7D

Add "nice" error pages for SSaaS failures