This commit is contained in:
Vylpes 2020-12-20 19:39:03 +00:00
parent cf003bea00
commit cc6b77884c
11 changed files with 5887 additions and 245 deletions

View file

@ -1,20 +0,0 @@
# Get the plugin for your editor and your
# tab settings will be set automatically.
# http://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style newlines with newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
# Indentation override for all JS under lib directory
[*.js]
indent_size = 4

2
.gitattributes vendored
View file

@ -1,2 +0,0 @@
* text=auto
*.js text eol=lf

2
.gitignore vendored
View file

@ -1,2 +1,2 @@
node_modules
app.js

1
.npmignore Normal file
View file

@ -0,0 +1 @@
app.js

View file

@ -1,11 +0,0 @@
sudo: false
language: node_js
node_js:
- 4
- 5
- 6
script:
- npm test

View file

@ -1,71 +1,41 @@
'use strict';
const fetch = require('node-fetch');
const got = require('got');
const uniqueRandomArray = require('unique-random-array');
const EventEmitter = require('eventemitter3');
sortable = [
'new',
'hot',
'top'
]
const randomCache = {};
function randomBunny(subreddit, sortBy, cb) {
if (!sortable.includes(sortBy)) sortBy = 'hot';
function formatResult(getRandomImage) {
const imageData = getRandomImage();
if (!imageData) {
return;
}
return `http://imgur.com/${imageData.hash}${imageData.ext.replace(/\?.*/, '')}`;
}
fetch(`https://www.reddit.com/r/${subreddit}/${sortBy}.json`).then(res => {
res.json().then(res => {
const data = res.data.children;
const size = data.length;
function storeResults(images, subreddit) {
const getRandomImage = uniqueRandomArray(images);
const random = getRandom(0, size - 1);
randomCache[subreddit] = getRandomImage;
return getRandomImage;
}
const image = data[random];
let found = false;
function randomPuppy(subreddit) {
subreddit = (typeof subreddit === 'string' && subreddit.length !== 0) ? subreddit : 'puppies';
while (!found) {
const random = getRandom(0, size - 1);
if (randomCache[subreddit]) {
return Promise.resolve(formatResult(randomCache[subreddit]));
}
const image = data[random].data['url'];
const title = data[random].data['title'];
return got(`https://imgur.com/r/${subreddit}/hot.json`, {json: true})
.then(response => storeResults(response.body.data, subreddit))
.then(getRandomImage => formatResult(getRandomImage));
}
// silly feature to play with observables
function all(subreddit) {
const eventEmitter = new EventEmitter();
function emitRandomImage(subreddit) {
randomPuppy(subreddit).then(imageUrl => {
eventEmitter.emit('data', imageUrl + '#' + subreddit);
if (eventEmitter.listeners('data').length) {
setTimeout(() => emitRandomImage(subreddit), 200);
if (image.includes('.jpg')) {
found = true;
cb(image, title);
}
}
});
}
emitRandomImage(subreddit);
return eventEmitter;
});
}
function callback(subreddit, cb) {
randomPuppy(subreddit)
.then(url => cb(null, url))
.catch(err => cb(err));
function getRandom(min, max) {
return Math.floor((Math.random() * max) + min);
}
// 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);
}
};
module.exports.all = all;
module.exports = randomBunny;

View file

@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) Dylan Greene <dylang@gmail.com> (github.com/dylang)
Copyright (c) Vylpes
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

5827
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -1,43 +1,25 @@
{
"name": "random-puppy",
"version": "1.1.0",
"description": "Get a random imgur image url, by default a puppy.",
"name": "random-bunny",
"version": "0.0.1",
"description": "Get a random subreddit image url",
"license": "MIT",
"repository": "dylang/random-puppy",
"author": {
"name": "Dylan Greene",
"email": "dylang@gmail.com",
"url": "github.com/dylang"
},
"engines": {
"node": ">=4.0.0"
},
"scripts": {
"test": "xo && ava",
"watch": "ava --watch"
},
"files": [
"index.js"
],
"author": "Vylpes",
"keywords": [
"puppy",
"doggie",
"dog",
"imgur",
"rabbit",
"bunny",
"bun",
"subreddit",
"reddit",
"random",
"placeholder"
],
"dependencies": {
"eventemitter3": "^1.2.0",
"got": "^6.3.0",
"unique-random-array": "^1.0.0"
"node-fetch": "^2.6.1"
},
"devDependencies": {
"ava": "^0.14.0",
"rx-lite": "^4.0.8",
"xo": "^0.14.0"
"scripts": {
"test": "echo \"No tests\""
},
"xo": {
"space": 4
}
"bugs": "https://gitlab.vylpes.com/Vylpes/random-bunny/-/issues",
"homepage": "https://gitlab.vylpes.com/Vylpes/random-bunny",
"funding": "https://ko-fi.com/gravitysoftware"
}

View file

@ -1,65 +1,40 @@
# random-puppy [![Build Status](https://travis-ci.org/dylang/random-puppy.svg?branch=master)](https://travis-ci.org/dylang/random-puppy)
# random-bunny
> Get a random puppy image url.
<img src="http://i.imgur.com/0zZ8m6B.jpg" width="300px">
> Get a random image url from a subreddit of your choosing.
## Install
```
$ npm install --save random-puppy
$ npm install --save random-bunny
```
## Usage
```js
const randomPuppy = require('random-puppy');
const randomBunny = require('random-bunny');
randomPuppy()
.then(url => {
console.log(url);
})
//=> 'http://imgur.com/IoI8uS5.jpg'
randomBunny('rabbits', 'new', (image, title) => {
console.log(title + ": " + image);
});
```
## API
### `randomPuppy()`
### `randomBunny()`
Returns a `promise` for a random puppy image url from http://imgur.com/ from https://www.reddit.com/r/puppy
### `randomPuppy(subreddit)`
Returns a `promise` for a random image url from the selected subreddit. *Warning: We cannot promise it will be a image of a puppy!*
### `randomPuppy.all(subreddit)`
Returns an `eventemitter` for getting all random images for a subreddit.
```js
const event = randomPuppy.all(subreddit);
event.on('data', url => console.log(url));
```
Or:
```js
const event = randomPuppy.all('puppies');
Observable.fromEvent(event, 'data')
.subscribe(data => {
console.log(data);
});
```
Returns a `url` and `title` for a random post to the `callback`. Accepts 3 arguments: `subreddit`, `sortby` ('new', 'hot', 'top'), `callback(image, title)`
## Notes
* Node 4 or newer.
* Caches results from imgur in memory.
* Created for the purpose of using in a training exercise on different ways to do async in JavaScript at [Opower](https://opower.com/).
* based upon [Random Puppy](https://github.com/dylang/random-puppy)
## Links
* Discord: [Server Link](https://discord.gg/UyAhAVp)
## License
MIT © [Dylan Greene](https://github.com/dylang)
MIT © [Vylpes](https://gitlab.vylpes.com/Vylpes);

80
test.js
View file

@ -1,80 +0,0 @@
import test from 'ava';
import {Observable} from 'rx-lite';
import randomPuppy from './';
const imgurRegEx = /^https?:\/\/(\w+\.)?imgur.com\/[a-zA-Z0-9]+(\.[a-zA-Z]{3})?(#[a-zA-Z]*)?$/;
test('get random', async t => {
const result = await randomPuppy();
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);
const result2 = await randomPuppy();
t.regex(result2, imgurRegEx);
const result3 = await randomPuppy();
t.regex(result3, imgurRegEx);
const result4 = await randomPuppy();
t.regex(result4, imgurRegEx);
});
test('different subreddit', async t => {
const result1 = await randomPuppy('aww');
t.regex(result1, imgurRegEx);
const result2 = await randomPuppy('aww');
t.regex(result2, imgurRegEx);
const result3 = await randomPuppy('aww');
t.regex(result3, imgurRegEx);
const result4 = await randomPuppy('aww');
t.regex(result4, imgurRegEx);
});
test('invalid subreddit', async t => {
const result1 = await randomPuppy('23rkljr2klj3');
t.falsy(result1);
const result2 = await randomPuppy('');
t.regex(result2, imgurRegEx);
const result3 = await randomPuppy({});
t.regex(result3, imgurRegEx);
const result4 = await randomPuppy(false);
t.regex(result4, imgurRegEx);
});
test('all', t => {
t.plan(10);
const puppyEmitter = randomPuppy.all('puppies');
const robotEmitter = randomPuppy.all('robots');
const puppySource = Observable.fromEvent(puppyEmitter, 'data');
const robotSource = Observable.fromEvent(robotEmitter, 'data');
const sharedSource = Observable
.merge(puppySource, robotSource)
.take(10);
sharedSource.subscribe(data => {
t.regex(data, imgurRegEx);
// console.log(data);
});
return sharedSource.toPromise();
});