Created
March 13, 2014 15:53
-
-
Save simenbrekken/9531078 to your computer and use it in GitHub Desktop.
Multi format store
This file contains hidden or 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 lodash = require('lodash'), | |
superagent = require('superagent'), | |
Promise = require('es6-promise').Promise | |
Store.prototype.get = function(url) { | |
if (lodash.isArray(url)) { | |
return Promise.all(lodash.map(url, this.get)) | |
} else if (lodash.isObject(url)) { | |
return Promise.all(lodash.map(url, function(url, key) { | |
return this.get(url).then(function(value) { | |
return [key, value] | |
}) | |
}, this)).then(lodash.zipObject) | |
} else { | |
return new Promise(function(resolve, reject) { | |
superagent('GET', url) | |
.set('Accept', 'application/json') | |
.end(function(err, res) { | |
if (err) return reject(err) | |
if (res.error) return reject(res.error.message) | |
resolve(res.body) | |
}) | |
}) | |
} | |
} | |
// Example: | |
var store = new Store() | |
store.get('http://google.com').then(function(content) { | |
console.log(content) // => a | |
}) | |
store.get(['http://a.com', 'http://b.com']).then(function(content) { | |
console.log(content) // => [a, b] | |
}) | |
store.get({products: 'http://a.com', navigation: 'http://b.com'}).then(function(content) { | |
console.log(content) // => {products: a, navigation: b} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment