Compare commits

..

No commits in common. "master" and "v1.2.1" have entirely different histories.

35 changed files with 2493 additions and 6770 deletions

View file

@ -1 +0,0 @@
dist/

View file

@ -44,7 +44,6 @@
"module": "writable",
"require": "writable",
"process": "writable",
"console": "writable",
"jest": "writable"
"console": "writable"
}
}

View file

@ -1,18 +0,0 @@
Epic: \
Story Points:
---
*No description*
## Acceptance Criteria
*No acceptance criteria*
## Subtasks
*No subtasks*
## Notes
*No notes*

View file

@ -1,29 +0,0 @@
# Description
Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change.
Fixes # (issue)
## Type of change
Please delete options that are not relevant.
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] This change requires a documentation update
# How Has This Been Tested?
Please describe the tests that you ran to verify the changes. Provide instructions so we can reproduce. Please also list any relevant details to your test configuration.
# Checklist
- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [ ] I have added tests that provde my fix is effective or that my feature works
- [ ] New and existing unit tests pass locally with my changes
- [ ] Any dependent changes have been merged and published in downstream modules

8
.gitignore vendored
View file

@ -1,6 +1,2 @@
node_modules/
dist/
bin/
coverage/
yarn-error.log
.DS_Store
node_modules
app.js

View file

@ -1,5 +1 @@
src/
bin/
tests/
jest.config.cjs
jest.setup.js
app.js

View file

@ -1,92 +0,0 @@
steps:
build:
# Build and test
image: node
commands:
- yarn install --frozen-lockfile
- yarn build
when:
event: [ push, pull_request ]
branch: [ hotfix/*, feature/*, renovate/*, develop, master ]
lint:
image: node
commands:
- yarn lint
when:
event: [ push, pull_request ]
branch: [ hotfix/*, feature/*, renovate/*, develop, master ]
test:
image: node
commands:
- yarn test
when:
event: [ push, pull_request ]
branch: [ hotfix/*, feature/*, renovate/*, develop, master ]
# Package production build
package_prod:
image: node
commands:
- apt install unzip -y
- wget https://github.com/xerub/ldid/releases/download/42/ldid.zip
- unzip ldid.zip
- mkdir /opt/ldid/
- cp linux64/ldid /opt/ldid/
- export PATH=/opt/ldid:$PATH
- yarn package
when:
event: push
branch: master
rsync_prod:
image: alpine
secrets: [ ssh_key ]
commands:
- apk add rsync openssh-client
- eval `ssh-agent -s`
- echo "$SSH_KEY" | tr -d '\r' | ssh-add -
- rsync -e "ssh -o StrictHostKeyChecking=no" -r ./bin vylpes@192.168.1.115:/home/vylpes/apps/random-bunny/random-bunny_prod
when:
event: push
branch: master
# Package stage build
package_stage:
image: node
commands:
- apt install unzip -y
- wget https://github.com/xerub/ldid/releases/download/42/ldid.zip
- unzip ldid.zip
- mkdir /opt/ldid/
- cp linux64/ldid /opt/ldid/
- export PATH=/opt/ldid:$PATH
- yarn package
when:
event: push
branch: develop
rsync_stage:
image: alpine
secrets: [ ssh_key ]
commands:
- apk add rsync openssh-client
- eval `ssh-agent -s`
- echo "$SSH_KEY" | tr -d '\r' | ssh-add -
- rsync -e "ssh -o StrictHostKeyChecking=no" -r ./bin vylpes@192.168.1.115:/home/vylpes/apps/random-bunny/random-bunny_stage
when:
event: push
branch: develop
# Publish to NPM
publish:
image: plugins/npm
settings:
username:
from_secret: NPM_USERNAME
email:
from_secret: NPM_EMAIL
password:
from_secret: NPM_PASSWORD
token:
from_secret: NPM_TOKEN
when:
event: push
branch: master

View file

@ -61,7 +61,7 @@ representative at an online or offline event.
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
[helpdesk@vylpes.com](mailto:helpdesk@vylpes.com).
[INSERT CONTACT METHOD].
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the

View file

@ -12,9 +12,7 @@ This project and everyone participating in it is governed by the Random Bunny Co
> **Note:** Please don't file an issue to ask a question. You'll get faster results by using the resources below.
You can ask a question about the project in the `#development` channel in the [Discord Server](https://go.vylpes.xyz/A6HcA).
You can also email with queries and support if you'd prefer at [helpdesk@vylpes.com](mailto:helpdesk@vylpes.com).
You can ask a question about the project in the `#development` channel in the [Discord Server](https://discord.gg/UyAhAVp).
## What you should know
@ -71,9 +69,18 @@ Provide more context by answering these questions:
Include details about your configuration and environment:
* **Which version of Random Bunny are you using?** You can get the exact version by running the `about` command.
* **Do you have any custom commands added to the commands folder?** If you do, provide information on what the command does, and a link to the command file if it exists.
> **Note:** We do not provide any support on issues caused by custom commands. You are welcome to create an issue if you believe the issue is to do with the base code, but if the error is to do with that custom command we are unable to fix that, you will need to contact the author of that command.
* **What's the name and version of the OS you're using?**
* **Are you running Random Bunny in a virtual machine?** If so, which VM software are you using and which operating systems and versions are used for the host and the guest?
* **What version of node do you have installed?** You can get this version by running the `node -v` command in your terminal.
* **What does your `config.json` file look like?**
> **Note:** remember to **not** give out your bot tokens which are inside of the `config.json` file. If you're giving a copy of your configuration remember to delete the tokens from the string and leave the empty.
* **Are you running the bot in live or dev mode?**
### Suggesting Enhancements
@ -83,7 +90,7 @@ When you are creating an enhancement suggestion, please include as many details
#### Before Submitting an Enhancement Suggestion
* **Check if the feature already exists.** Make sure to check on the latest version
* **Check if the feature already exists.** Make sure to check on the latest version and if you can get the desired behaviour using the config options inside of `config.json`
* **Perform a search** to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one.
#### How Do I Submit A (Good) Enhancement Suggestion?
@ -108,14 +115,15 @@ You'll need the following tools:
* Git
* NodeJS
* Yarn
Install and build all of the dependencies using `npm`
```bash
cd random-bunny
yarn install
cd Random Bunny
npm install
cp config.json.template config.json
```
And then use your text editor of choice to fill in the `config.json` file.
#### Build and Run
@ -124,24 +132,22 @@ If you want to understand how Random Bunny works or want to debug an issue, you'
First, fork the Random Bunny repository so that you can make a pull request. Then, clone your fork locally:
```bash
git clone https://gitea.vylpes.xyz/<your-gitea-account>/random-bunny.git
# OR
git clone https://codeberg.org/vylpes/random-bunny.git
git clone https://gitlab.vylpes.com/<your-gitlab-account>/random-bunny.git
```
Occasionally, you will want to merge changes in the upstream repository (the official code repo) with your fork.
```bash
cd random-bunny
cd Random Bunny
git checkout master
git pull https://gitea.vylpes.xyz/vylpes/random-bunny.git master
git pull https://gitlab.vylpes.com/vylpes/random-bunny.git master
```
Manage any merge conflicts, commit them, and then push them to your fork.
Go into `random-bunny` and build the package using `yarn build`.
Go into `Random Bunny` and start the bot in dev mode with `npm run dev` or `node bot dev`
> **Note:** If you have `nodemon` installed on your system you can use this during development so it auto restarts when you make code changes. Instead of the commands above you can then run `nodemon bot dev`.
#### Pull Requests
@ -163,14 +169,6 @@ Please follow these steps to have your contribution considered by maintainers:
While the prerequesites above must be satisifed prior to having your pull reuqest accepted, the reviewer(s) may ask you to complete additional design ork, tests, or other changes before your pull request can be ultimately accepted.
#### Submitting Changes via Email
If you're not within our gitea instance and still like to contribute, you can send us your contributions to [git@vylpes.com](mailto:git@vylpes.com).
For more information on how to do this, see the [git documentation](https://git-scm.com/docs/git-send-email).
#### Submitting Changes via Codeberg
This code is mirrored on codeberg, although main development is done on my self-hosted Gitea instance, feel free to clone and create pull requests on there. I will merge it back into Gitea once accepted.
#### JavaScript Styleguide
All JavaScript code is linted with `eslint`.
@ -196,10 +194,7 @@ function ban (member) {
}).catch(err => {
// handle error here
});
}
```
# Contributing to Random Bunny
}# Contributing to Random Bunny
First off, thanks for taking the time to contribute!
@ -213,7 +208,7 @@ This project and everyone participating in it is governed by the Random Bunny Co
> **Note:** Please don't file an issue to ask a question. You'll get faster results by using the resources below.
You can ask a question about the project in the `#development` channel in the [Discord Server](https://go.vylpes.xyz/A6HcA).
You can ask a question about the project in the `#development` channel in the [Discord Server](https://discord.gg/UyAhAVp).
## What you should know
@ -233,4 +228,170 @@ We won't accept pull requests unless these checks pass. If yours fail, simply fi
* **Arrow body style** should have braces around the body only when needed
* **Arrow parameters** should have brackets around them only when needed
* **Arrow spacing** should have a space around the arrow (' => ')
* **No var** should be used, instead use either let or const when appropriate
* **No var** should be used, instead use either let or const when appropriate
## How You Can Contribute
### Reporting Bugs
This section guides you through submitting a bug report for Random Bunny. Following these guidelines helps maintainers and the community understand your report. reproduce the behaviour, and find related reports.
When you are creating a bug report, please include as many details as possible.
> **Note:** If you find a **Closed** issue that seems like it is the same thing that you're experiencing, open a new issue and include a link to the original issue in the body of your new one.
#### Before Submitting A Bug Report
* **Perform a search** to see if the problem has already been reported. If it has **and the issue is still open**, add a comment to the existing issue instead of opening a new one.
#### How You Can Submit A (Good) Bug Report
Bugs are tracked as GitHub issues. After you've determined the bug you're reporting hasn't got a pre-existing **open** issue already, create an issue and provide information from below.
* **Use a clear and descriptive title** for the issue to indentify the problem.
* **Describe the exact steps which reproduce the problem** in as many details as possible. For example, start by explaining how you started Random Bunny (if you're using your own instance), which command exactly you used, and the output which the bot replied with. If its your own instance, provide information on what the terminal output said, if any.
* **Provide specific examples to demonstrate the steps**. Include links to files or GitHub projects, or copy/pastable snippets, which you use in those examples. If you're providing snippets in the issue, use Markdown code blocks.
* **Describe the behaviour you observed after following the steps** and point out what exactly is the problem with that behaviour.
* **Explain which behaviour you expected to see instead and why.**
* **Include screenshots and animated GIFs** which show you following the described steps and clearly demonstrate the problem.
* **If the problem wasn't triggered by a specific action**, describe what you were doing before the problem happened and share more information using the guidelines below.
Provide more context by answering these questions:
* **Did the problem start happening recently** (e.g. after updating to a new version of Random Bunny) or was this always a problem?
* If the problem started happening recently, **can you reproduce the problem in an older version of Random Bunny?** What's the most recently version in which the problem doesn't happen? You can download older versions of Random Bunny from the releases page.
* **Can you reliably reproduce the issue?** If not, provide details about how often the problem happens and under which conditions it normally happens.
Include details about your configuration and environment:
* **Which version of Random Bunny are you using?** You can get the exact version by running the `about` command.
* **Do you have any custom commands added to the commands folder?** If you do, provide information on what the command does, and a link to the command file if it exists.
> **Note:** We do not provide any support on issues caused by custom commands. You are welcome to create an issue if you believe the issue is to do with the base code, but if the error is to do with that custom command we are unable to fix that, you will need to contact the author of that command.
* **What's the name and version of the OS you're using?**
* **Are you running Random Bunny in a virtual machine?** If so, which VM software are you using and which operating systems and versions are used for the host and the guest?
* **What version of node do you have installed?** You can get this version by running the `node -v` command in your terminal.
* **What does your `config.json` file look like?**
> **Note:** remember to **not** give out your bot tokens which are inside of the `config.json` file. If you're giving a copy of your configuration remember to delete the tokens from the string and leave the empty.
* **Are you running the bot in live or dev mode?**
### Suggesting Enhancements
This section guides you through submitting an enhancement suggestion for Random Bunny, including completely new features and minor improvements to existing functionality. Following these guidelines helps maintainers and the community understand your suggestion and find related suggestions.
When you are creating an enhancement suggestion, please include as many details as possible. Fill out the suggestion with the steps that you imagine you would take if the feature you're requesting existed.
#### Before Submitting an Enhancement Suggestion
* **Check if the feature already exists.** Make sure to check on the latest version and if you can get the desired behaviour using the config options inside of `config.json`
* **Perform a search** to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one.
#### How Do I Submit A (Good) Enhancement Suggestion?
Enhancement suggestions are tracked as GitHub issues. After you've determined the feature doesn't already exist or been suggested before, create an issue on that repository and provide the following information:
* **Use a clear and descriptive title** for the issue to identify the suggestion.
* **Provide a step-by-step description of the suggested enhancement** in as many details as possible.
* **Provide specific examples to demonstrate the steps.** Include copy/pastable snippets which you use in those examples, as Markdown code blocks.
* **Describe the current behaviour** and **explain which behaviour you expected to see instead** and why.
* **Include screnshots and animated GIFs** which help you demonstrate the steps or point out the part of Random Bunny which the suggestion is related to.
* **Explain why this enhancement would be useful** to most Random Bunny users and isn't something that can or should be implemented as a custom command.
* **List some other bots where this enhancement exists.**
* **Specify which version of Random Bunny you're using.** You can get the exact version by running the `about` command.
* **Specify the name and version of the OS you're using.**
### Your First Code Contribution
Unsure where to begin contributing to Random Bunny? You can start by looking through these `good first` and `help wanted` issues
#### Prerequisites
In order to download necessary tools, clone the repository, and install dependencies via `npm` you need network access.
You'll need the following tools:
* Git
* NodeJS
Install and build all of the dependencies using `npm`
```bash
cd Random Bunny
npm install
cp config.json.template config.json
```
And then use your text editor of choice to fill in the `config.json` file.
#### Build and Run
If you want to understand how Random Bunny works or want to debug an issue, you'll want to get the source, build it, and run the tool locally.
First, fork the Random Bunny repository so that you can make a pull request. Then, clone your fork locally:
```bash
git clone https://gitlab.vylpes.com/<your-gitlab-account>/random-bunny.git
```
Occasionally, you will want to merge changes in the upstream repository (the official code repo) with your fork.
```bash
cd Random Bunny
git checkout master
git pull https://github.com/getgravitysoft/random-bunny.git master
```
Manage any merge conflicts, commit them, and then push them to your fork.
Go into `Random Bunny` and start the bot in dev mode with `npm run dev` or `node bot dev`
> **Note:** If you have `nodemon` installed on your system you can use this during development so it auto restarts when you make code changes. Instead of the commands above you can then run `nodemon bot dev`.
#### Pull Requests
The process described here has several goals:
* Maintain Random Bunny's quality
* Fix problems that are important to users
* Engage the community in working toward the best possible Random Bunny
* Enable a sustainable system for Random Bunny's maintainers to review contributions
Please follow these steps to have your contribution considered by maintainers:
* You mention the issue id which this pull request aims to fix
* After you submit your pull request, verify that all status checks are passing.
> **Note**: If a check fails the pull request it is important that you go and fix these issues, or let us know that you no longer want to work on this issue by commenting on the pull request. Doing this will give you a better chance of having your pull request merged.
* When the checks have passed a maintainer will review your code and ask for any improvements or questions, and will merge it if they are satisifed.
While the prerequesites above must be satisifed prior to having your pull reuqest accepted, the reviewer(s) may ask you to complete additional design ork, tests, or other changes before your pull request can be ultimately accepted.
#### JavaScript Styleguide
All JavaScript code is linted with `eslint`.
* Prefer camelcase for variable names
* Prefer braces `{` to be on the same line
* Prefer no comma `,` dangle
* Prefer arrow function bodies to have brances `{}` only when needed
* Prefer arrow function parameters to have brackets `()` only when needed
* Prefer arrow function arrows `=>` to have a space before and after it
* Prefer `let` and `const` over `var`
As well as eslint's recommended defaults.
Example
```js
function ban (member) {
let reason = "Example reason";
member.ban(reason).then(() => {
// handle then here
}).catch(err => {
// handle error here
});
}

View file

@ -1,6 +1,6 @@
MIT License
Copyright (c) 2020-2023 Vylpes
Copyright (c) 2020 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

View file

@ -1,97 +0,0 @@
# CLI
Since Version 2.2, Random Bunny contains a command line interface (CLI).
## Downloads
The project can be downloaded as a binary for your system via the [GitHub Releases](https://github.com/Vylpes/random-bunny/releases) or [Gitea Releases](https://gitea.vylpes.xyz/RabbitLabs/random-bunny/releases) page.
We currently support:
- Linux (x64)
- Windows (x64)
- macOS (x64, Arm64\*)
The git repository can also be cloned and ran via `yarn build` and `yarn start`.
> **NOTE:** We are aware of a bug in the macOS Arm64 builds failing to execute. For now you're still able to use the x64 builds under Rosetta fine. This will hopefully be fixed in a future release.
## Default Output
By default, the command will fetch a random image from `r/rabbits` and return it in a human-readable output.
```
$ randombunny
Archived = false
Downvotes = 0
Hidden = false
Permalink = /r/Rabbits/comments/1av1rg9/cute_baby_bun/
Subreddit = Rabbits
Subreddit Subscribers = 486084
Title = Cute baby bun
Upvotes = 211
Url = https://i.redd.it/sfz0srdrimjc1.png
```
## Help
The command also includes a help option in case you are stuck.
```
$ randombunny --help
# or
$ randombunny -h
Usage: random-bunny [options]
Get a random image url from a subreddit of your choosing
Options:
-V, --version output the version number
-s, --subreddit <subreddit> The subreddit to search (default: "rabbits")
-j, --json Output as JSON
-q, --query-metadata Include query metadata in result
--sort <sort> Sort by (choices: "hot", "new", "top", default: "hot")
-h, --help display help for command
✨ Done in 0.32s.
```
## JSON output
You can also convert the output into JSON, if you need to input it to another program.
```bash
$ randombunny --json
# or
$ randonbunny -j
{"Archived":false,"Downs":0,"Hidden":false,"Permalink":"/r/Rabbits/comments/1av1rg9/cute_baby_bun/","Subreddit":"Rabbits","SubredditSubscribers":486085,"Title":"Cute baby bun","Ups":210,"Url":"https://i.redd.it/sfz0srdrimjc1.png"}
```
## Sort
You can also choose the sorting option which reddit will use to return the available posts to randomise from.
This defaults to "hot". The valid options are "hot", "new", and "top".
```
$ randombunny --sort hot
$ randombunny --sort new
$ randomBunny --sort top
```
## Subreddit
You can change the subreddit which the command fetches from.
This defaults to "rabbits"
```
$ randombunny --subreddit rabbits
$ randombunny -s horses
```

121
index.js Normal file
View file

@ -0,0 +1,121 @@
// Required Modules
const fetch = require('node-fetch');
// Valid sortBy names
const sortable = [
'new',
'hot',
'top'
]
// Main function
function randomBunny(subreddit, sortBy, cb) {
// If the sortable list doesn't include sortBy, default to 'hot'
if (!sortable.includes(sortBy)) sortBy = 'hot';
// Fetch the json from reddit
// For example, if you're getting a random image from r/rabbits, sorted by new:
// https://www.reddit.com/r/rabbits/new.json
fetch(`https://www.reddit.com/r/${subreddit}/${sortBy}.json`).then(res => {
res.json().then(res => {
// Get the part of the json string which the data comes from
const data = res.data.children;
const size = data.length;
// Found is used for the while loop in order to break out of the loop.
// We need to loop as the json string will contain invalid data for what we need
// Specifically videos.
let found = false;
// Loop until a valid image post is found
while (!found) {
// Generate random number
const random = getRandom(0, size - 1);
// Get variables from json to pass back
const randomSelect = data[random].data;
// The json string to send back
const json = {
archived: randomSelect['archived'],
downs: randomSelect['downs'],
hidden: randomSelect['hidden'],
permalink: randomSelect['permalink'],
subreddit: randomSelect['subreddit'],
subredditSubscribers: randomSelect['subreddit_subscribers'],
title: randomSelect['title'],
ups: randomSelect['ups'],
url: randomSelect['url']
};
// If the post is a .jpg, send back the data and stop looping
if (json.url.includes('.jpg')) {
found = true;
cb(json);
}
}
});
});
}
function promise(subreddit, sortBy) {
return new Promise(resolve => {
// If the sortable list doesn't include sortBy, default to 'hot'
if (!sortable.includes(sortBy)) sortBy = 'hot';
// Fetch the json from reddit
// For example, if you're getting a random image from r/rabbits, sorted by new:
// https://www.reddit.com/r/rabbits/new.json
fetch(`https://www.reddit.com/r/${subreddit}/${sortBy}.json`).then(res => {
res.json().then(res => {
// Get the part of the json string which the data comes from
const data = res.data.children;
const size = data.length;
// Found is used for the while loop in order to break out of the loop.
// We need to loop as the json string will contain invalid data for what we need
// Specifically videos.
let found = false;
// Loop until a valid image post is found
while (!found) {
// Generate random number
const random = getRandom(0, size - 1);
// Get variables from json to pass back
const randomSelect = data[random].data;
// The json string to send back
const json = {
archived: randomSelect['archived'],
downs: randomSelect['downs'],
hidden: randomSelect['hidden'],
permalink: randomSelect['permalink'],
subreddit: randomSelect['subreddit'],
subredditSubscribers: randomSelect['subreddit_subscribers'],
title: randomSelect['title'],
ups: randomSelect['ups'],
url: randomSelect['url']
};
// If the post is a .jpg, send back the data and stop looping
if (json.url.includes('.jpg')) {
found = true;
resolve(json);
}
}
});
});
})
}
// Generate a random number
function getRandom(min, max) {
return Math.floor((Math.random() * max) + min);
}
// Export Functions
module.exports = {
randomBunny,
promise,
};

View file

@ -1,4 +0,0 @@
module.exports = {
preset: "ts-jest",
setupFiles: [ "./jest.setup.js" ]
}

View file

@ -1,3 +0,0 @@
jest.setTimeout(1 * 1000); // 1 second
jest.resetModules();
jest.resetAllMocks();

21
license Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 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
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

2126
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -1,13 +1,9 @@
{
"name": "random-bunny",
"version": "2.2.0",
"version": "1.2.1",
"description": "Get a random subreddit image url",
"license": "MIT",
"author": "Vylpes",
"exports": "./dist/index.js",
"typings": "./dist/index.d.ts",
"bin": "./dist/cli.js",
"main": "./dist/index.js",
"keywords": [
"rabbit",
"bunny",
@ -18,57 +14,18 @@
"placeholder"
],
"dependencies": {
"commander": "^12.0.0",
"glob-parent": "^6.0.0",
"got-cjs": "^12.5.4",
"htmlparser2": "^9.1.0",
"linqts": "^1.14.4"
"node-fetch": "^2.6.1"
},
"scripts": {
"build": "tsc",
"start": "node dist/cli.js",
"test": "jest",
"lint": "eslint .",
"release": "np --no-publish",
"package": "pkg . --no-bytecode"
"test": "echo none",
"lint": "eslint ."
},
"bugs": {
"url": "https://gitea.vylpes.xyz/RabbitLabs/random-bunny/issues",
"email": "helpdesk@vylpes.com"
"bugs": "https://github.com/Vylpes/random-bunny/issues",
"homepage": "https://github.com/Vylpes/random-bunny",
"funding": {
"url": "https://ko-fi.com/vylpes"
},
"homepage": "https://gitea.vylpes.xyz/RabbitLabs/random-bunny",
"funding": "https://ko-fi.com/vylpes",
"devDependencies": {
"@types/eslint": "^8.21.1",
"@types/jest": "^29.5.8",
"@types/node": "^20.0.0",
"@typescript-eslint/eslint-plugin": "^7.0.0",
"@typescript-eslint/parser": "^5.54.0",
"eslint": "^8.49.0",
"jest": "^29.7.0",
"jest-mock-extended": "^3.0.3",
"np": "^9.0.0",
"pkg": "^5.8.1",
"ts-jest": "^29.1.1",
"ts-mockito": "^2.6.1",
"typescript": "^5.0.0"
},
"resolutions": {
"np/**/got": "^14.0.0",
"**/semver": "^7.5.2",
"@babel/traverse": "^7.23.2"
},
"files": [
"dist"
],
"pkg": {
"scripts": "dist/**/*.js",
"targets": [
"latest-linux-x64",
"latest-macos-x64",
"latest-macos-arm64",
"latest-win-x64"
],
"outputPath": "bin"
"eslint": "^7.17.0"
}
}

View file

@ -4,36 +4,34 @@
## Install
```bash
npm install --save random-bunny
```
or if you're using yarn
```bash
yarn add random-bunny
$ npm install --save random-bunny
```
### Binary
The project can be downloaded as a binary for your system via the [GitHub Releases](https://github.com/Vylpes/random-bunny/releases) or [Gitea Releases](https://gitea.vylpes.xyz/RabbitLabs/random-bunny/releases) page.
## Usage
```ts
import randomBunny from "random-bunny";
```js
const { randomBunny } = require('random-bunny');
// ... In an async function
const result = await randomBunny('rabbits', 'hot');
console.log(result);
randomBunny('rabbits', 'new', res => {
console.log(res.title + ": " + res.url);
});
```
```js
const { promise } = require('random-bunny');
promise('rabbits', 'new').then((res) => {
console.log(res.title);
});
```
## API
### `randomBunny()`
Returns a `json string` for a random post. Accepts 2 arguments: `subreddit`, and `sortby` ('new', 'hot', 'top')
Returns a `json string` for a random post to the `callback`. Accepts 3 arguments: `subreddit`, `sortby` ('new', 'hot', 'top'), `callback(res)`
The json string which gets returned consists of:
- archived
@ -46,13 +44,11 @@ The json string which gets returned consists of:
- ups
- url
`sortBy` will default to 'hot' if not given or invalid
### `promise()`
## CLI
Returns a `json string` for a random post in a `promise`. Accepts 2 arguments: `subreddit`, `sortby` ('new', 'hot', 'top').
Random bunny can also be used as a CLI. This is accessible via the executable (see git releases) or via `src/cli.ts`
For more details, see the [documentation](https://docs.vylpes.xyz/books/random-bunny).
The json string returned in the promise consists of the same above.
## Notes
@ -61,9 +57,8 @@ For more details, see the [documentation](https://docs.vylpes.xyz/books/random-b
## Links
* Discord: [Server Link](https://go.vylpes.xyz/A6HcA)
* Support: [helpdesk@vylpes.com](mailto:helpdesk@vylpes.com)
* Discord: [Server Link](https://discord.gg/UyAhAVp)
## License
MIT © [Vylpes](https://www.vylpes.com)
MIT © [Vylpes](https://gitlab.vylpes.com/Vylpes)

View file

@ -1,4 +0,0 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"baseBranches": ["develop"]
}

View file

@ -1,56 +0,0 @@
import { Command, Option } from "commander";
import randomBunny from "./index";
import ICliOptions from "./contracts/ICliOptions";
import { exit } from "process";
const program = new Command();
program
.name('random-bunny')
.description('Get a random image url from a subreddit of your choosing')
.version('2.2')
.option('-s, --subreddit <subreddit>', 'The subreddit to search', 'rabbits')
.option('-j, --json', 'Output as JSON')
.option('-q, --query-metadata', 'Include query metadata in result')
.addOption(new Option('--sort <sort>', 'Sort by').default('hot').choices(['hot', 'new', 'top']));
program.parse();
const options: ICliOptions = program.opts();
randomBunny(options.subreddit, options.sort)
.then((response) => {
if (response.IsSuccess) {
const result = response.Result!;
const outputLines: string[] = [];
if (options.json) {
console.log(JSON.stringify(result));
return;
}
outputLines.push(`Archived = ${result.Archived}`);
outputLines.push(`Downvotes = ${result.Downs}`);
outputLines.push(`Hidden = ${result.Hidden}`);
outputLines.push(`Permalink = ${result.Permalink}`);
outputLines.push(`Subreddit = ${result.Subreddit}`);
outputLines.push(`Subreddit Subscribers = ${result.SubredditSubscribers}`);
outputLines.push(`Title = ${result.Title}`);
outputLines.push(`Upvotes = ${result.Ups}`);
outputLines.push(`Url = ${result.Url}`);
if (options.queryMetadata != null) {
outputLines.push(`Query.Subreddit = ${response.Query.subreddit}`);
outputLines.push(`Query.Sort By = ${response.Query.sortBy}`);
}
console.log(outputLines.join("\n"));
exit(0);
} else {
const error = response.Error!;
console.error(error.Message, error.Code);
exit(1);
}
});

View file

@ -1,6 +0,0 @@
export enum ErrorCode {
Unknown,
FailedToFetchReddit,
UnableToParseJSON,
NoImageResultsFound,
}

View file

@ -1,5 +0,0 @@
export default class ErrorMessages {
public static readonly FailedToFetchReddit = "Failed to fetch result from Reddit";
public static readonly UnableToParseJSON = "Unable to parse the JSON result";
public static readonly NoImageResultsFound = "No image results found in response from Reddit";
}

View file

@ -1,6 +0,0 @@
export default interface ICliOptions {
subreddit: string,
json?: boolean,
sort: string,
queryMetadata?: boolean,
}

View file

@ -1,6 +0,0 @@
import { ErrorCode } from "../constants/ErrorCode";
export default interface IError {
Code: ErrorCode;
Message: string;
}

View file

@ -1,13 +0,0 @@
export default interface IFetchResult {
data: {
archived: boolean,
downs: number,
hidden: boolean,
permalink: string,
subreddit: string,
subreddit_subscribers: number,
title: string,
ups: number,
url: string
}
}

View file

@ -1,11 +0,0 @@
export default interface IRedditResult {
Archived: boolean,
Downs: number,
Hidden: boolean,
Permalink: string,
Subreddit: string,
SubredditSubscribers: number,
Title: string,
Ups: number,
Url: string
}

View file

@ -1,10 +0,0 @@
import IError from "./IError.js";
import IRedditResult from "./IRedditResult.js";
import QueryResult from "./QueryResult.js";
export default interface IReturnResult {
IsSuccess: boolean;
Query: QueryResult;
Result?: IRedditResult;
Error?: IError;
}

View file

@ -1,4 +0,0 @@
export default interface QueryResult {
subreddit: string,
sortBy: string,
}

View file

@ -1,19 +0,0 @@
import fetch from "got-cjs";
import * as htmlparser from "htmlparser2";
export default class ImageHelper {
public static async FetchImageFromRedditGallery(url: string): Promise<string | undefined> {
const fetched = await fetch(url);
if (!fetched || fetched.errored || fetched.statusCode != 200) {
return undefined;
}
const dom = htmlparser.parseDocument(fetched.body);
const img = htmlparser.DomUtils.findOne((x => x.tagName == "img" && x.attributes.find(y => y.value.includes("https://preview.redd.it")) != null), dom.children, true);
const imgSrc = img?.attributes.find(x => x.name == "src")?.value;
return imgSrc;
}
}

View file

@ -1,129 +0,0 @@
import IReturnResult from "./contracts/IReturnResult";
import IRedditResult from "./contracts/IRedditResult";
import fetch from "got-cjs";
import { List } from 'linqts';
import IFetchResult from "./contracts/IFetchResult";
import { ErrorCode } from "./constants/ErrorCode";
import ErrorMessages from "./constants/ErrorMessages";
import ImageHelper from "./imageHelper";
const sortable = [
'new',
'hot',
'top'
];
export default async function randomBunny(subreddit: string, sortBy: string = 'hot'): Promise<IReturnResult> {
if (!sortable.includes(sortBy)) sortBy = 'hot';
const result = await fetch(`https://reddit.com/r/${subreddit}/${sortBy}.json?limit=100`)
.then((res) => {
return res;
})
.catch(() => {
return null;
});
if (!result) {
return {
IsSuccess: false,
Query: {
subreddit: subreddit,
sortBy: sortBy,
},
Error: {
Code: ErrorCode.FailedToFetchReddit,
Message: ErrorMessages.FailedToFetchReddit,
},
}
}
const json = JSON.parse(result.body);
if (!json) {
return {
IsSuccess: false,
Query: {
subreddit: subreddit,
sortBy: sortBy,
},
Error: {
Code: ErrorCode.UnableToParseJSON,
Message: ErrorMessages.UnableToParseJSON,
},
}
}
const data: IFetchResult[] = json.data.children;
const dataWithImages = new List<IFetchResult>(data)
.Where(x => x!.data.url.includes('.jpg') || x!.data.url.includes('.png') || x!.data.url.includes("/gallery/"))
.ToArray();
let random = 0;
if (dataWithImages.length == 0) {
return {
IsSuccess: false,
Query: {
subreddit: subreddit,
sortBy: sortBy,
},
Error: {
Code: ErrorCode.NoImageResultsFound,
Message: ErrorMessages.NoImageResultsFound,
},
};
} else {
random = Math.floor((Math.random() * (dataWithImages.length - 1)) + 0); // Between 0 and (size - 1)
}
const randomSelect = dataWithImages[random];
const randomData = randomSelect.data;
let url: string;
if (randomData.url.includes("/gallery")) {
const galleryImage = await ImageHelper.FetchImageFromRedditGallery(randomData.url);
if (!galleryImage) {
return {
IsSuccess: false,
Query: {
subreddit: subreddit,
sortBy: sortBy,
},
Error: {
Code: ErrorCode.NoImageResultsFound,
Message: ErrorMessages.NoImageResultsFound,
},
}
}
url = galleryImage;
} else {
url = randomData.url;
}
const redditResult: IRedditResult = {
Archived: randomData['archived'],
Downs: randomData['downs'],
Hidden: randomData['hidden'],
Permalink: randomData['permalink'],
Subreddit: randomData['subreddit'],
SubredditSubscribers: randomData['subreddit_subscribers'],
Title: randomData['title'],
Ups: randomData['ups'],
Url: url,
};
return {
IsSuccess: true,
Query: {
subreddit: subreddit,
sortBy: sortBy,
},
Result: redditResult
};
}

View file

@ -1,187 +0,0 @@
import { exec } from "child_process";
import path from "path";
describe('default', () => {
test('GIVEN no options are supplied, EXPECT standard output', async () => {
const result = await cli([], '.');
const keys = result.stdout.split('\n')
.flatMap(x => x.split(' = ')[0])
.filter(x => x && x.length > 0);
const values = result.stdout.split('\n')
.flatMap(x => x.split(' = ')[1])
.filter(x => x && x.length > 0);
expect(result.code).toBe(0);
expect(keys).toStrictEqual(['Archived', 'Downvotes', 'Hidden', 'Permalink', 'Subreddit', 'Subreddit Subscribers', 'Title', 'Upvotes', 'Url']);
expect(values.length).toBe(9);
}, 5000);
test('GIVEN an error occurs, EXPECT error output', async () => {
const result = await cli(['-s', 'textonly'], '.');
expect(result.code).toBe(1);
expect(result.stderr).toBeDefined();
}, 5000);
});
describe('version', () => {
test('GIVEN -V flag is supplied, EXPECT version returned', async () => {
const result = await cli(['-V'], '.');
expect(result.code).toBe(0);
expect(result.stdout).toBe('2.2\n');
});
test('GIVEN --version is supplied, EXPECT version returned', async () => {
const result = await cli(['--version'], '.');
expect(result.code).toBe(0);
expect(result.stdout).toBe('2.2\n');
});
});
describe('help', () => {
test('GIVEN -h is supplied, EXPECT help returned', async () => {
const result = await cli(['-h'], '.');
expect(result.code).toBe(0);
expect(result.stdout.split('\n')[0]).toBe('Usage: random-bunny [options]');
});
test('GIVEN --help is supplied, EXPECT help returned', async () => {
const result = await cli(['--help'], '.');
expect(result.code).toBe(0);
expect(result.stdout.split('\n')[0]).toBe('Usage: random-bunny [options]');
});
});
describe('subreddit', () => {
test('GIVEN -s is not supplied, EXPECT subreddit to be defaulted', async () => {
const result = await cli([], '.');
const subreddit = result.stdout.split('\n')
.find(x => x && x.length > 0 && x.split(' = ')[0] == 'Subreddit')!
.split(' = ')[1];
expect(subreddit).toBe('Rabbits');
}, 5000);
test('GIVEN -s is supplied, EXPECT subreddit to be changed', async () => {
const result = await cli(['-s', 'pics'], '.');
const subreddit = result.stdout.split('\n')
.find(x => x && x.length > 0 && x.split(' = ')[0] == 'Subreddit')!
.split(' = ')[1];
expect(subreddit).toBe('pics');
}, 5000);
test('GIVEN --subreddit is supplied, EXPECT subreddit to be changed', async () => {
const result = await cli(['--subreddit', 'pics'], '.');
const subreddit = result.stdout.split('\n')
.find(x => x && x.length > 0 && x.split(' = ')[0] == 'Subreddit')!
.split(' = ')[1];
expect(subreddit).toBe('pics');
}, 5000);
});
describe('json', () => {
test('GIVEN -j is supplied, EXPECT output to be valid JSON', async () => {
const result = await cli(['-j'], '.');
const json = JSON.parse(result.stdout);
expect(json).toBeDefined();
}, 5000);
test('GIVEN --json is supplied, EXPECT output to be valid JSON', async () => {
const result = await cli(['--json'], '.');
const json = JSON.parse(result.stdout);
expect(json).toBeDefined();
}, 5000);
});
describe('sort', () => {
test('GIVEN --sort is not supplied, EXPECT sort to be defaulted', async () => {
const result = await cli(['-q'], '.');
const sortBy = result.stdout.split('\n')
.find(x => x && x.length > 0 && x.split(' = ')[0] == 'Query.Sort By')!
.split(' = ')[1];
expect(sortBy).toBe('hot');
}, 5000);
test('GIVEN --sort is supplied WITH a valid input, EXPECT sort to be used', async () => {
const result = await cli(['-q', '--sort', 'new'], '.');
const sortBy = result.stdout.split('\n')
.find(x => x && x.length > 0 && x.split(' = ')[0] == 'Query.Sort By')!
.split(' = ')[1];
expect(sortBy).toBe('new');
}, 5000);
test('GIVEN --sort is supplied WITH an invalid input, EXPECT error', async () => {
const result = await cli(['-q', '--sort', 'invalid'], '.');
expect(result.code).toBe(1);
expect(result.stderr).toBe("error: option '--sort <sort>' argument 'invalid' is invalid. Allowed choices are hot, new, top.\n");
}, 5000);
});
describe('query-metadata', () => {
test('GIVEN --query-metadata is not supplied, EXPECT no query metadata returned', async () => {
const result = await cli([], '.');
const query = result.stdout.split('\n')
.find(x => x && x.length > 0 && x.split(' = ')[0].startsWith('Query'));
expect(query).toBeUndefined();
}, 5000);
test('GIVEN --query-metadata is supplied, EXPECT query metadata returned', async () => {
const result = await cli(['--query-metadata'], '.');
const query = result.stdout.split('\n')
.find(x => x && x.length > 0 && x.split(' = ')[0].startsWith('Query'));
expect(query).toBeDefined();
}, 5000);
test('GIVEN -q is supplied, EXPECT query metadata returned', async () => {
const result = await cli(['-q'], '.');
const query = result.stdout.split('\n')
.find(x => x && x.length > 0 && x.split(' = ')[0].startsWith('Query'));
expect(query).toBeDefined();
}, 5000);
});
function cli(args: string[], cwd: string): Promise<cliResult> {
return new Promise(resolve => {
exec(`node ${path.resolve('./dist/cli.js')} ${args.join(' ')}`,
{ cwd },
(error, stdout, stderr) => { resolve({
code: error && error.code ? error.code : 0,
error,
stdout,
stderr });
});
});
}
interface cliResult {
code: number,
error: any,
stdout: string,
stderr: string,
}

View file

@ -1,90 +0,0 @@
import ImageHelper from "../src/imageHelper";
import fetch from "got-cjs";
jest.mock('got-cjs');
const fetchMock = jest.mocked(fetch);
describe("FetchImageFromRedditGallery", () => {
test("EXPECT image url to be returned", async () => {
fetchMock.mockResolvedValue({
body: "<html><body><img src='https://preview.redd.it/image.png' /></body></html>",
errored: undefined,
statusCode: 200,
});
const result = await ImageHelper.FetchImageFromRedditGallery("https://redd.it/gallery/image");
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledWith("https://redd.it/gallery/image");
expect(result).toBe("https://preview.redd.it/image.png");
});
test("GIVEN fetch is unable to return data, EXPECT undefined returned", async () => {
fetchMock.mockResolvedValue(null);
const result = await ImageHelper.FetchImageFromRedditGallery("https://redd.it/gallery/image");
expect(result).toBeUndefined();
});
test("GIVEN fetch is an error, EXPECT undefined returned", async () => {
fetchMock.mockResolvedValue({
body: "<html><body><img src='https://preview.redd.it/image.png' /></body></html>",
errored: "Error",
statusCode: 200,
});
const result = await ImageHelper.FetchImageFromRedditGallery("https://redd.it/gallery/image");
expect(result).toBeUndefined();
});
test("GIVEN fetch is not status code of 200, EXPECT undefined returned", async () => {
fetchMock.mockResolvedValue({
body: "<html><body><img src='https://preview.redd.it/image.png' /></body></html>",
errored: undefined,
statusCode: 500,
});
const result = await ImageHelper.FetchImageFromRedditGallery("https://redd.it/gallery/image");
expect(result).toBeUndefined();
});
test("GIVEN image tag is not found, EXPECT undefined returned", async () => {
fetchMock.mockResolvedValue({
body: "<html><body></body></html>",
errored: undefined,
statusCode: 200,
});
const result = await ImageHelper.FetchImageFromRedditGallery("https://redd.it/gallery/image");
expect(result).toBeUndefined();
});
test("GIVEN image source attribute is not found, EXPECT undefined returned", async () => {
fetchMock.mockResolvedValue({
body: "<html><body><img /></body></html>",
errored: undefined,
statusCode: 200,
});
const result = await ImageHelper.FetchImageFromRedditGallery("https://redd.it/gallery/image");
expect(result).toBeUndefined();
});
test("GIVEN image source attribute is not found that is a preview.redd.it url, EXPECT undefined returned", async () => {
fetchMock.mockResolvedValue({
body: "<html><body><img src='main.png' /></body></html>",
errored: undefined,
statusCode: 200,
});
const result = await ImageHelper.FetchImageFromRedditGallery("https://redd.it/gallery/image");
expect(result).toBeUndefined();
});
});

View file

@ -1,266 +0,0 @@
import { ErrorCode } from "../src/constants/ErrorCode";
import ErrorMessages from "../src/constants/ErrorMessages";
import ImageHelper from "../src/imageHelper";
import randomBunny from "../src/index";
import fetch from "got-cjs";
jest.mock('got-cjs');
const fetchMock = jest.mocked(fetch);
describe('randomBunny', () => {
test('GIVEN subreddit AND sortBy is supplied, EXPECT successful result', async() => {
fetchMock.mockResolvedValue({
body: JSON.stringify({
data: {
children: [
{
data: {
archived: false,
downs: 0,
hidden: false,
permalink: '/r/Rabbits/comments/12pa5te/someone_told_pickles_its_monday_internal_fury/',
subreddit: 'Rabbits',
subreddit_subscribers: 298713,
title: 'Someone told pickles its Monday… *internal fury*',
ups: 1208,
url: 'https://i.redd.it/cr8xudsnkgua1.jpg',
},
},
],
}
}),
});
const result = await randomBunny('rabbits', 'new');
expect(result.IsSuccess).toBeTruthy();
expect(result.Result).toBeDefined();
expect(result.Error).toBeUndefined();
expect(fetchMock).toBeCalledWith('https://reddit.com/r/rabbits/new.json?limit=100');
});
test('GIVEN sortBy is NOT supplied, expect it to default to hot', async () => {
fetchMock.mockResolvedValue({
body: JSON.stringify({
data: {
children: [
{
data: {
archived: false,
downs: 0,
hidden: false,
permalink: '/r/Rabbits/comments/12pa5te/someone_told_pickles_its_monday_internal_fury/',
subreddit: 'Rabbits',
subreddit_subscribers: 298713,
title: 'Someone told pickles its Monday… *internal fury*',
ups: 1208,
url: 'https://i.redd.it/cr8xudsnkgua1.jpg',
},
},
],
}
}),
});
const result = await randomBunny('rabbits');
expect(result.IsSuccess).toBeTruthy();
expect(result.Result).toBeDefined();
expect(result.Error).toBeUndefined();
expect(fetchMock).toBeCalledWith('https://reddit.com/r/rabbits/hot.json?limit=100');
});
test('GIVEN sortBy is NOT valid, expect it to default to hot', async () => {
fetchMock.mockResolvedValue({
body: JSON.stringify({
data: {
children: [
{
data: {
archived: false,
downs: 0,
hidden: false,
permalink: '/r/Rabbits/comments/12pa5te/someone_told_pickles_its_monday_internal_fury/',
subreddit: 'Rabbits',
subreddit_subscribers: 298713,
title: 'Someone told pickles its Monday… *internal fury*',
ups: 1208,
url: 'https://i.redd.it/cr8xudsnkgua1.jpg',
},
},
],
}
}),
});
const result = await randomBunny('rabbits', 'invalid');
expect(result.IsSuccess).toBeTruthy();
expect(result.Result).toBeDefined();
expect(result.Error).toBeUndefined();
expect(fetchMock).toBeCalledWith('https://reddit.com/r/rabbits/hot.json?limit=100');
});
test('GIVEN the fetch fails, EXPECT failure result', async () => {
fetchMock.mockRejectedValue('Test Reason')
const result = await randomBunny('rabbits', 'new');
expect(result.IsSuccess).toBeFalsy();
expect(result.Result).toBeUndefined();
expect(result.Error).toBeDefined();
expect(result.Error!.Code).toBe(ErrorCode.FailedToFetchReddit);
expect(result.Error!.Message).toBe(ErrorMessages.FailedToFetchReddit);
expect(fetchMock).toBeCalledWith('https://reddit.com/r/rabbits/new.json?limit=100');
});
test('GIVEN the result is NOT valid JSON, EXPECT failure result', async () => {
fetchMock.mockResolvedValue({
body: JSON.stringify(null),
});
const result = await randomBunny('rabbits', 'new');
expect(result.IsSuccess).toBeFalsy();
expect(result.Result).toBeUndefined();
expect(result.Error).toBeDefined();
expect(result.Error!.Code).toBe(ErrorCode.UnableToParseJSON);
expect(result.Error!.Message).toBe(ErrorMessages.UnableToParseJSON);
expect(fetchMock).toBeCalledWith('https://reddit.com/r/rabbits/new.json?limit=100');
});
test('GIVEN randomSelect does NOT find a response, EXPECT failure result', async () => {
fetchMock.mockResolvedValue({
body: JSON.stringify({
data: {
children: [],
}
}),
});
const result = await randomBunny('rabbits', 'new');
expect(result.IsSuccess).toBeFalsy();
expect(result.Result).toBeUndefined();
expect(result.Error).toBeDefined();
expect(result.Error!.Code).toBe(ErrorCode.NoImageResultsFound);
expect(result.Error!.Message).toBe(ErrorMessages.NoImageResultsFound);
expect(fetchMock).toBeCalledWith('https://reddit.com/r/rabbits/new.json?limit=100');
});
test('GIVEN randomSelect does NOT find a valid response, EXPECT failure result', async () => {
fetchMock.mockResolvedValue({
body: JSON.stringify({
data: {
children: [
{
data: {
archived: false,
downs: 0,
hidden: false,
permalink: '/r/Rabbits/comments/12pa5te/someone_told_pickles_its_monday_internal_fury/',
subreddit: 'Rabbits',
subreddit_subscribers: 298713,
title: 'Someone told pickles its Monday… *internal fury*',
ups: 1208,
url: 'https://i.redd.it/cr8xudsnkgua1.webp',
},
},
],
}
}),
});
const result = await randomBunny('rabbits', 'new');
expect(result.IsSuccess).toBeFalsy();
expect(result.Result).toBeUndefined();
expect(result.Error).toBeDefined();
expect(result.Error!.Code).toBe(ErrorCode.NoImageResultsFound);
expect(result.Error!.Message).toBe(ErrorMessages.NoImageResultsFound);
expect(fetchMock).toBeCalledWith('https://reddit.com/r/rabbits/new.json?limit=100');
expect(fetchMock).toBeCalledWith('https://reddit.com/r/rabbits/new.json?limit=100');
});
test("GIVEN data fetched is a gallery AND an image is returned from the helper, EXPECT this to be used", async () => {
fetchMock.mockResolvedValue({
body: JSON.stringify({
data: {
children: [
{
data: {
archived: false,
downs: 0,
hidden: false,
permalink: '/r/Rabbits/comments/12pa5te/someone_told_pickles_its_monday_internal_fury/',
subreddit: 'Rabbits',
subreddit_subscribers: 298713,
title: 'Someone told pickles its Monday… *internal fury*',
ups: 1208,
url: 'https://i.redd.it/gallery/cr8xudsnkgua1',
},
},
],
}
}),
});
ImageHelper.FetchImageFromRedditGallery = jest.fn().mockResolvedValue("https://i.redd.it/cr8xudsnkgua1.jpg")
const result = await randomBunny('rabbits', 'new');
expect(result.IsSuccess).toBeTruthy();
expect(result.Result).toBeDefined();
expect(fetchMock).toBeCalledWith('https://reddit.com/r/rabbits/new.json?limit=100');
expect(ImageHelper.FetchImageFromRedditGallery).toHaveBeenCalledTimes(1);
expect(ImageHelper.FetchImageFromRedditGallery).toHaveBeenCalledWith("https://i.redd.it/gallery/cr8xudsnkgua1");
});
test("GIVEN data fetched is a gallery AND an image is not returned from the helper, EXPECT error", async () => {
fetchMock.mockResolvedValue({
body: JSON.stringify({
data: {
children: [
{
data: {
archived: false,
downs: 0,
hidden: false,
permalink: '/r/Rabbits/comments/12pa5te/someone_told_pickles_its_monday_internal_fury/',
subreddit: 'Rabbits',
subreddit_subscribers: 298713,
title: 'Someone told pickles its Monday… *internal fury*',
ups: 1208,
url: 'https://i.redd.it/gallery/cr8xudsnkgua1',
},
},
],
}
}),
});
ImageHelper.FetchImageFromRedditGallery = jest.fn().mockResolvedValue(undefined)
const result = await randomBunny('rabbits', 'new');
expect(ImageHelper.FetchImageFromRedditGallery).toHaveBeenCalledTimes(1);
expect(result.IsSuccess).toBe(false);
expect(result.Error).toBeDefined();
expect(result.Error?.Code).toBe(ErrorCode.NoImageResultsFound);
expect(result.Error?.Message).toBe(ErrorMessages.NoImageResultsFound);
});
});

View file

@ -1,83 +0,0 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "ES2020", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
"module": "Node16", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
"declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
/* Module Resolution Options */
"moduleResolution": "node16", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"include": [
"./src",
],
"exclude": [
"./tests",
"jest.config.cjs",
"jest.setup.js"
],
"ts-node": {
"esm": true
}
}

5510
yarn.lock

File diff suppressed because it is too large Load diff