From 4af799c68089d2a56f69fc67c4c0cd9c82d176b8 Mon Sep 17 00:00:00 2001 From: Trygve Laugstøl Date: Sat, 30 Jun 2012 01:18:33 +0200 Subject: o Prettier and better error handling. --- routes/index.js | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) (limited to 'routes') diff --git a/routes/index.js b/routes/index.js index 6d57023..bceafc3 100644 --- a/routes/index.js +++ b/routes/index.js @@ -2,6 +2,14 @@ var http = require('http') , url = require('url') , collection_json = require('collection_json'); +function urlgenerator(req) { + var host = req.headers.host; + return { + render: function(u) { + return 'http://' + host + '/render?url=' + encodeURIComponent(u)} + }; +} + exports.index = function(req, res){ res.render('index', { title: 'Collection+JSON Explorer', @@ -17,14 +25,23 @@ exports.index = function(req, res){ }); }; -exports.render = function(req, res){ +exports.render = function(req, res) { + function sendErr(err) { + res.render('data', { + url: req.query.url, + err: err + }); + } fetchCollection(req.query.url, function(err, headers, body) { if(err) { - res.render('index', { title: 'Failed to render ' + req.query.url }); + sendErr(err); } else { - var parsedBody = JSON.parse(body); - var doc = collection_json.fromObject(parsedBody); + var parsedBody; + try { + parsedBody = JSON.parse(body); + } catch(e) { sendErr('Unable to parse JSON: ' + e); } + var doc = collection_json.fromObject(parsedBody).collection; var isUrl = function(u) { try { var x = url.parse(u); @@ -36,6 +53,7 @@ exports.render = function(req, res){ }; res.render('data', { isUrl: isUrl, + urlgenerator: urlgenerator(req), url: req.query.url, doc: doc, headers: headers, -- cgit v1.2.3