diff --git a/index.js b/index.js index d1a6467..c4ebcdc 100644 --- a/index.js +++ b/index.js @@ -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); + } }; diff --git a/package.json b/package.json index ac1cf6e..eeacb79 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/test.js b/test.js index f3c1a90..63ea031 100644 --- a/test.js +++ b/test.js @@ -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);