Skip to content

Instantly share code, notes, and snippets.

@simenbrekken
Created March 13, 2014 15:53
Show Gist options
  • Save simenbrekken/9531078 to your computer and use it in GitHub Desktop.
Save simenbrekken/9531078 to your computer and use it in GitHub Desktop.
Multi format store
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