Skip to content

Commit

Permalink
.get() now returns a promise if you don\'t pass a callback function
Browse files Browse the repository at this point in the history
  • Loading branch information
swang committed Apr 21, 2019
1 parent 14d6c4d commit 39a18b0
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 2 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,16 @@ marvel.events
})
})
```
## call as a promise
if you would like to use this library with promises, new in v1.2.0 is the ability to return a promise if you decide not to pass in a callback function to `get()`

example:
```js
marvel.events.name('civil war').get().then(function(results) {
console.log(results);
})
```


# documentation

Expand Down
16 changes: 14 additions & 2 deletions lib/resource.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,20 @@ Resource = function(resource, opts) {
Resource.prototype.hash = function(ts) {
return crypto.createHash('md5').update(String(ts) + this.privateKey + this.publicKey).digest('hex')
}

Resource.prototype.get = function(cb) {
var self = this;
if (!cb && typeof Promise !== 'undefined') {
return new Promise(function(resolve, reject) {
self._get(function(err, res) {
if (err) return reject(err)
return resolve(res)
})
})
} else {
self._get(cb)
}
}
Resource.prototype._get = function(cb) {
var uri
var qs
var ts = +new Date()
Expand Down Expand Up @@ -91,7 +103,7 @@ Resource.prototype.get = function(cb) {
} catch(e) {
return cb(new Error('Result returned was not a JSON'))
}
return cb(null, pBody.data.results, pBody)
return cb(null, pBody.data && pBody.data.results, pBody)
})
})
res.on('error', function(e) {
Expand Down
30 changes: 30 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,34 @@ describe('marvel.characters.*.get', function() {
resp[0].should.have.properties('comics', 'series', 'stories', 'events', 'urls', 'thumbnail', 'resourceURI')
})
})

})

describe('marvel.characters.*.get (as a promise)', function() {
var marvelGet, marvel, json

beforeEach(function() {
marvel = new Marvel({
publicKey: 'xxx',
privateKey: 'yyy'
})
marvelGet = sinon.stub(marvel.characters, 'get')
json = require('./fixtures/character-hulk.json') // eslint-disable-line global-require
marvelGet.resolves(json)
})
afterEach(function() {
marvelGet.restore()
})

it('should return hulk data using a promise', function() {
marvel.characters.name('Hulk').get().then(function(resp) {
resp[0].id.should.eql(1009351)
resp[0].name.should.eql('Hulk')
resp[0].resourceURI.should.eql('http://gateway.marvel.com/v1/public/characters/1009351')
resp[0].should.have.properties('comics', 'series', 'stories', 'events', 'urls', 'thumbnail', 'resourceURI')
}).catch(function(err) {
should.not.exist(err)
})
})

})

0 comments on commit 39a18b0

Please sign in to comment.