Compare commits

..

No commits in common. "master" and "v2.0.5" have entirely different histories.

31 changed files with 529 additions and 5958 deletions

22
.drone.yml Normal file
View file

@ -0,0 +1,22 @@
kind: pipeline
name: integration
steps:
- name: build
image: node
commands:
- yarn install --frozen-lockfile
- name: test
image: node
commands:
- yarn test
depends_on:
- build
trigger:
branch:
- develop
- feature/*
- hotfix/*
event:
- push

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

9
.gitignore vendored
View file

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

View file

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

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

@ -196,10 +196,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!

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

9
app.ts Normal file
View file

@ -0,0 +1,9 @@
import randomBunny from "./dist";
async function app() {
const result = await randomBunny('rabbits', 'hot', 100);
console.log(result);
}
app();

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
```

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.

View file

@ -1,13 +1,11 @@
{
"name": "random-bunny",
"version": "2.2.0",
"version": "2.0.5",
"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",
"typings": "./dist/index.d.ts",
"keywords": [
"rabbit",
"bunny",
@ -18,19 +16,15 @@
"placeholder"
],
"dependencies": {
"commander": "^12.0.0",
"glob-parent": "^6.0.0",
"got-cjs": "^12.5.4",
"htmlparser2": "^9.1.0",
"got": "^11.8.3",
"linqts": "^1.14.4"
},
"scripts": {
"build": "tsc",
"start": "node dist/cli.js",
"test": "jest",
"lint": "eslint .",
"release": "np --no-publish",
"package": "pkg . --no-bytecode"
"start": "ts-node app.ts",
"test": "echo none",
"lint": "eslint ."
},
"bugs": {
"url": "https://gitea.vylpes.xyz/RabbitLabs/random-bunny/issues",
@ -39,36 +33,12 @@
"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"
"@types/node": "^16.11.11",
"eslint": "^7.17.0",
"ts-node": "^10.4.0",
"typescript": "^4.5.2"
},
"files": [
"dist"
],
"pkg": {
"scripts": "dist/**/*.js",
"targets": [
"latest-linux-x64",
"latest-macos-x64",
"latest-macos-arm64",
"latest-win-x64"
],
"outputPath": "bin"
}
]
}

View file

@ -14,10 +14,6 @@ or if you're using yarn
yarn add 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
@ -25,7 +21,7 @@ The project can be downloaded as a binary for your system via the [GitHub Releas
import randomBunny from "random-bunny";
// ... In an async function
const result = await randomBunny('rabbits', 'hot');
const result = await randomBunny('rabbits', 'hot', 100);
console.log(result);
```
@ -33,7 +29,7 @@ console.log(result);
### `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. Accepts 3 arguments: `subreddit`, `sortby` ('new', 'hot', 'top'), `maxTries?` (default 100)
The json string which gets returned consists of:
- archived
@ -48,11 +44,7 @@ The json string which gets returned consists of:
`sortBy` will default to 'hot' if not given or invalid
## CLI
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).
`maxTries` prevents the script from rerolling too many times. The script rerolls the randomiser if the post its given doesn't contain an image. Default 100.
## Notes

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,10 +1,6 @@
import IError from "./IError.js";
import IRedditResult from "./IRedditResult.js";
import QueryResult from "./QueryResult.js";
import IRedditResult from "./IRedditResult";
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,11 +1,8 @@
import IReturnResult from "./contracts/IReturnResult";
import IRedditResult from "./contracts/IRedditResult";
import fetch from "got-cjs";
import fetch from "got";
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',
@ -13,28 +10,14 @@ const sortable = [
'top'
];
export default async function randomBunny(subreddit: string, sortBy: string = 'hot'): Promise<IReturnResult> {
if (!sortable.includes(sortBy)) sortBy = 'hot';
export default async function randomBunny(subreddit: string, sortBy?: string, maxTries = 100): Promise<IReturnResult> {
if (!sortBy || !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;
});
const result = await fetch(`https://reddit.com/r/${subreddit}/${sortBy}.json`);
if (!result) {
return {
IsSuccess: false,
Query: {
subreddit: subreddit,
sortBy: sortBy,
},
Error: {
Code: ErrorCode.FailedToFetchReddit,
Message: ErrorMessages.FailedToFetchReddit,
},
IsSuccess: false
}
}
@ -42,88 +25,44 @@ export default async function randomBunny(subreddit: string, sortBy: string = 'h
if (!json) {
return {
IsSuccess: false,
Query: {
subreddit: subreddit,
sortBy: sortBy,
},
Error: {
Code: ErrorCode.UnableToParseJSON,
Message: ErrorMessages.UnableToParseJSON,
},
IsSuccess: false
}
}
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/"))
.Where(x => x!.data.url.includes('.jpg') || x!.data.url.includes('.png'))
.ToArray();
let random = 0;
for (let i = 0; i < maxTries; i++) {
const random = Math.floor((Math.random() * dataWithImages.length - 1) + 0); // Between 0 and (size - 1)
if (dataWithImages.length == 0) {
return {
IsSuccess: false,
Query: {
subreddit: subreddit,
sortBy: sortBy,
},
Error: {
Code: ErrorCode.NoImageResultsFound,
Message: ErrorMessages.NoImageResultsFound,
},
const randomSelect = dataWithImages[random];
if (!randomSelect) continue;
const randomData = randomSelect.data;
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: randomData['url']
};
return {
IsSuccess: true,
Result: redditResult
};
} 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
};
IsSuccess: false
}
}

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,11 +1,11 @@
{
"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'. */
"module": "commonjs", /* 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. */
@ -23,7 +23,7 @@
// "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. */
@ -33,7 +33,7 @@
// "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. */
@ -42,9 +42,9 @@
// "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). */
"moduleResolution": "node", /* 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. */
@ -54,17 +54,17 @@
"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. */
@ -73,11 +73,7 @@
"./src",
],
"exclude": [
"./tests",
"jest.config.cjs",
"jest.setup.js"
],
"ts-node": {
"esm": true
}
"./tests"
]
}

5294
yarn.lock

File diff suppressed because it is too large Load diff