TL;DR
If you want to improve the readability of your API Proxies running on Apigee. Use Promises instead of plain Callbacks. Here's Apigee Cache Promise NPM Module to help you get started.
--------
A few days ago I worked on refactoring some old but critical code that I wrote in JavaScript with callbacks. It leveraged our great Apigee Access NPM official module. However, there was some code smells because it was based on a bunch of nested callbacks that made it hard to debug and troubleshoot. So, I decided that I should refactor it using Promises and finally get out of the rat race.
For those unfamiliar with the benefits of Promises, there's lots of documentation written about this topic, but I'd recommend reading You're missing the point of Promises. So, I won't bore you explaining it here. Suffice to say; it will make your code way more readable without sacrificing the benefits of Node.js. And the best thing is that you can Promisify any callback-based library without having to rewrite any of the internals of such library.
var apigee = require('apigee-access'), cache = apigee.getCache(), apigee_cache_promise = require('apigee-cache-promise')(cache); apigee_cache_promise.get('cache_key') .then(function(cached_value) { console.log(cached_value); return JSON.parse(cached_value); }) .then(function(cached_value) { //do more stuff }) .catch(function(e){ console.log('something failed!'); })
apigee_cache_promise.put('cache_key', '{"test": "test_val"}', 300 // 5 minutes) .then(function() { console.log('Successfully stored in cache'); }) .then(function(cached_value) { //do more stuff }) .catch(function(e) { console.log('something failed!'); })
apigee_cache_promise.remove('cache_key') .then(function() { console.log('Successfully removed from cache'); }) .then(function(cached_value) { //do more stuff }) .catch(function(e) { console.log('something failed!'); })
That's it, folks!
What do you think about it? Love or hate promises? Do you use Apigee Cache? Maybe a version of RxJS would be the next iteration of this article? Leave your comments below.
Stay tuned!
Diego