"use strict";

var redis   = require("redis"),
    client  = redis.createClient(),
    _       = require("underscore"),
    Fetcher = require("l2b-price-fetchers");


function getBookDetails (isbn, cb) {

  var cacheKey = "details-" + isbn;

  client.get(cacheKey, function (err, reply) {
    if ( reply ) {
      cb( null, JSON.parse(reply) );
    } else {
      fetchFromScrapers(
        {vendor: "foyles", isbn: isbn },
        function (err, results) {
          if (err) { return cb(err); }
          var returnData = _.pick(results, "isbn", "authors", "title");
          // TODO perhaps put an expiry in here...
          client.set(cacheKey, JSON.stringify(returnData));
          cb(null, returnData);
        }
      );
    }
  });

}

function fetchFromScrapers (options, cb) {
  var f = new Fetcher();
  f.fetch(
    options,
    function (err, data) {
      if (err) { return cb(err); }
      cb(null, data);
    }
  );
}


module.exports = {
  getBookDetails: getBookDetails,
};

@@ -160,16 +160,85 @@
 rs%22);%0A%0A%0A
+function bookDetailsCacheKey (isbn) %7B%0A  return %22details-%22 + isbn;%0A%7D%0A%0A
 function
@@ -284,33 +284,41 @@
 heKey = 
-%22d
+bookD
 etails
--%22 + 
+CacheKey(
 isbn
+)
 ;%0A%0A  cli
@@ -585,225 +585,550 @@
 var 
-returnData = _.pick(results, %22isbn%22, %22authors%22, %22title%22);%0A          // TODO perhaps put an expiry in here...%0A          client.set(cacheKey, JSON.stringify(returnData));%0A          cb(null, returnData);%0A        %7D%0A      
+bookDetails = extractBookDetails(results);%0A          cb(null, bookDetails);%0A        %7D%0A      );%0A    %7D%0A  %7D);%0A%0A%7D%0A%0Afunction extractBookDetails (results) %7B%0A  return _.pick(results, %22isbn%22, %22authors%22, %22title%22);%0A%7D%0A%0A%0Afunction cacheBookDetails (data) %7B%0A  var isbn = data.isbn;%0A  var cacheKey = bookDetailsCacheKey(isbn);%0A%0A  client.exists(cacheKey, function (err, exists) %7B%0A    if (!err && !exists) %7B%0A      // TODO perhaps put an expiry in here...%0A      var bookDetails = extractBookDetails(data);%0A      client.set(cacheKey, JSON.stringify(bookDetails)
 );%0A 
@@ -1134,32 +1134,33 @@
     %7D%0A  %7D);%0A%0A%7D%0A%0A
+%0A
 function fetchFr
@@ -1293,24 +1293,54 @@
  cb(err); %7D%0A
+      cacheBookDetails(data);%0A
       cb(nul

Tidy up the book details caching