Created
September 20, 2015 19:49
-
-
Save cmstead/163632c67ba7d6bebeeb to your computer and use it in GitHub Desktop.
Request cache factory in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var cacheFactory = (function(){ | |
'use strict'; | |
function RequestCache(requestFn){ | |
this.callQueue = queueFactory.build(); | |
this.requestFn = requestFn; | |
this.dataCache = { | |
requestSent: false, | |
response: null | |
}; | |
} | |
RequestCache.prototype = { | |
resolveCache: function(){ | |
var data = this.dataCache.response.data, | |
error = this.dataCache.response.error; | |
while(this.callQueue.peek() !== null){ | |
this.callQueue.dequeue()(data, error); | |
} | |
}, | |
resolve: function(data, error){ | |
this.dataCache.response = { | |
data: data, | |
error: error | |
}; | |
this.resolveCache(); | |
}, | |
request: function(callback){ | |
var resolve = this.resolve.bind(this); | |
this.callQueue.enqueue(callback); | |
if(this.dataCache.response !== null){ | |
this.resolveCache(); | |
} | |
//Only send the request once. | |
else if (!this.requestSent) { | |
this.requestFn(resolve); | |
} | |
} | |
}; | |
function buildCache(requestFn){ | |
return new RequestCache(requestFn); | |
} | |
return { | |
build: buildCache | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment