diff --git a/lib/cache/CacheHandler.js b/lib/cache/CacheHandler.js index 8d2c1df7..1437ec7a 100644 --- a/lib/cache/CacheHandler.js +++ b/lib/cache/CacheHandler.js @@ -76,7 +76,7 @@ function getCacheByHref(cacheManager, href) { //href is almost never null, but it is in the case of an AuthenticationResult (at the moment), so check for existence: //see: https://github.com/stormpath/stormpath-sdk-node/issues/11 if (href) { - region = href.match(/customData/) ? 'customData' : (href.split('/').slice(-2)[0]); + region = href.split('/')[4]; } if (!region || CACHE_REGIONS.indexOf(region) === -1) { @@ -87,8 +87,23 @@ function getCacheByHref(cacheManager, href) { } CacheHandler.prototype.get = function getCachedResource(href, callback) { - var _this = this; - return getCacheByHref(_this.cacheManager, href).get(href, callback); + var _this = this; + if ( process.env.NODE_DEBUG_SP ) { console.log( 'Fetching CACHE resource:', href ); } + return getCacheByHref(_this.cacheManager, href).get(href, function( err, data ) { + if ( err ) { return callback( err ); } + if ( ! data ) { return callback( err, data ); } + async.eachSeries( _.keys( data ), function( key, cb ) { + var val = data[ key ]; + if ( ! ( val && val.href ) ) { return cb(); } + _this.get( val.href, function( err, val ) { + if ( err ) { return cb( err ); } + if ( val ) { data[ key ] = val; } + cb(); + }); + }, function( err ) { + return callback( err, data ); + }); + }); }; /* @@ -124,6 +139,12 @@ function buildCacheableResourcesFromParentObject(object){ resourcesToCache.push(parentResource); } } + + // Don't forget to cache the parent! + if ( object.href !== parentResource.href ) { + resourcesToCache.push( object ); + } + return resourcesToCache; } @@ -137,11 +158,12 @@ CacheHandler.prototype.put = function cacheResource(href, data, _new, cb) { async.each( buildCacheableResourcesFromParentObject(data), - function(resource,next) { - getCacheByHref(_this.cacheManager, resource.href) - .put(resource.href, resource, _new, next); - }, - cb + function(resource,next) { + if ( process.env.NODE_DEBUG_SP ) { console.log( 'Storing CACHE resource:', resource.href ); } + getCacheByHref(_this.cacheManager, resource.href) + .put(resource.href, resource, _new, next); + }, + cb ); }; diff --git a/lib/ds/RequestExecutor.js b/lib/ds/RequestExecutor.js index 8df49e1a..8c93e535 100644 --- a/lib/ds/RequestExecutor.js +++ b/lib/ds/RequestExecutor.js @@ -89,7 +89,9 @@ RequestExecutor.prototype.execute = function executeRequest(req, callback) { this.requestAuthenticator.authenticate(options); + var _s = new Date().getTime(); request(options, function onRequestResult(err, response, body) { + if ( process.env.NODE_DEBUG_SP ) { console.log( 'Fetched stormpath resource:', options.uri, '=> latency(ms):', new Date().getTime() - _s ); } if (err) { var wrapper = new Error('Unable to execute http request ' + req + ': ' + err.message); wrapper.inner = err;