callback support

This commit is contained in:
Dylan Greene 2016-04-28 11:31:41 -04:00
parent 1872153847
commit 57d00504f4
3 changed files with 44 additions and 3 deletions

View file

@ -20,7 +20,7 @@ function storeResults(images, subreddit) {
return getRandomImage;
}
module.exports = function (subreddit) {
function randomPuppy(subreddit) {
subreddit = (typeof subreddit === 'string' && subreddit.length !== 0) ? subreddit : 'puppies';
if (randomCache[subreddit]) {
@ -30,4 +30,22 @@ module.exports = function (subreddit) {
return got(`https://imgur.com/r/${subreddit}/hot.json`, {json: true})
.then(response => storeResults(response.body.data, subreddit))
.then(getRandomImage => formatResult(getRandomImage));
}
function callback(subreddit, cb) {
randomPuppy(subreddit)
.then(url => cb(null, url))
.catch(err => cb(err));
}
// subreddit is optional
// callback support is provided for a training exercise
module.exports = (subreddit, cb) => {
if (typeof cb === 'function') {
callback(subreddit, cb);
} else if (typeof subreddit === 'function') {
callback(null, subreddit);
} else {
return randomPuppy(subreddit);
}
};

View file

@ -1,6 +1,6 @@
{
"name": "random-puppy",
"version": "1.0.0",
"version": "1.0.1",
"description": "Get a random puppy image url.",
"license": "MIT",
"repository": "dylang/random-puppy",
@ -19,7 +19,12 @@
"index.js"
],
"keywords": [
"puppy", "doggie", "dog", "imgur", "random", "placeholder"
"puppy",
"doggie",
"dog",
"imgur",
"random",
"placeholder"
],
"dependencies": {
"got": "^6.3.0",

18
test.js
View file

@ -8,6 +8,24 @@ test('get random', async t => {
t.regex(result, imgurRegEx);
});
test.cb('use callback', t => {
t.plan(2);
randomPuppy((err, result) => {
t.falsy(err);
t.regex(result, imgurRegEx);
t.end();
});
});
test.cb('use callback and different subreddit', t => {
t.plan(2);
randomPuppy('aww', (err, result) => {
t.falsy(err);
t.regex(result, imgurRegEx);
t.end();
});
});
test('get more random', async t => {
const result1 = await randomPuppy();
t.regex(result1, imgurRegEx);