diff --git a/src/cli.ts b/src/cli.ts index 6f0639f..d103e86 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -10,6 +10,7 @@ program .description('Get a random image url from a subreddit of your choosing') .version('2.2') .option('-s, --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 by').default('hot').choices(['hot', 'new', 'top'])); @@ -23,6 +24,12 @@ randomBunny(options.subreddit, options.sort) 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}`); diff --git a/src/contracts/ICliOptions.ts b/src/contracts/ICliOptions.ts index ce5ada4..cc3af03 100644 --- a/src/contracts/ICliOptions.ts +++ b/src/contracts/ICliOptions.ts @@ -1,5 +1,6 @@ export default interface ICliOptions { subreddit: string, + json?: boolean, sort: string, queryMetadata?: boolean, } \ No newline at end of file diff --git a/tests/cli.test.ts b/tests/cli.test.ts index 1b04e47..9671235 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -90,6 +90,24 @@ describe('subreddit', () => { }, 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'], '.'); @@ -116,7 +134,7 @@ describe('sort', () => { expect(result.code).toBe(1); expect(result.stderr).toBe("error: option '--sort ' argument 'invalid' is invalid. Allowed choices are hot, new, top.\n"); - }); + }, 5000); }); describe('query-metadata', () => {