Skip to content

Commit

Permalink
refactor: rename a few more fetch functions (#1077)
Browse files Browse the repository at this point in the history
| 🚥 Resolves ISSUE_ID |
| :------------------- |

## 🧰 Changes

Describe in detail what this PR is for.

## 🧬 QA & Testing

Provide as much information as you can on how to test what you've done.
  • Loading branch information
kanadgupta authored Nov 20, 2024
1 parent b5d0603 commit e864491
Show file tree
Hide file tree
Showing 16 changed files with 121 additions and 123 deletions.
72 changes: 36 additions & 36 deletions __tests__/lib/fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import nock from 'nock';
import { describe, beforeEach, afterEach, it, expect, vi, beforeAll, type MockInstance } from 'vitest';

import pkg from '../../package.json' with { type: 'json' };
import { cleanHeaders, handleRes, readmeAPIV1Fetch } from '../../src/lib/readmeAPIFetch.js';
import { cleanAPIv1Headers, handleAPIv1Res, readmeAPIv1Fetch } from '../../src/lib/readmeAPIFetch.js';
import { getAPIV1Mock } from '../helpers/get-api-mock.js';
import { after, before } from '../helpers/setup-gha-env.js';

describe('#readmeAPIV1Fetch()', () => {
describe('#readmeAPIv1Fetch()', () => {
beforeAll(() => {
nock.disableNetConnect();
});
Expand All @@ -29,10 +29,10 @@ describe('#readmeAPIV1Fetch()', () => {
return this.req.headers;
});

const headers = await readmeAPIV1Fetch('/api/v1', {
const headers = await readmeAPIv1Fetch('/api/v1', {
method: 'get',
headers: cleanHeaders(key),
}).then(handleRes);
headers: cleanAPIv1Headers(key),
}).then(handleAPIv1Res);

expect(headers['user-agent']).toBe(`rdme-github/${pkg.version}`);
expect(headers['x-readme-source']).toBe('cli-gh');
Expand All @@ -56,14 +56,14 @@ describe('#readmeAPIV1Fetch()', () => {
return this.req.headers;
});

const headers = await readmeAPIV1Fetch(
const headers = await readmeAPIv1Fetch(
'/api/v1',
{
method: 'get',
headers: cleanHeaders(key),
headers: cleanAPIv1Headers(key),
},
{ filePath: 'openapi.json', fileType: 'path' },
).then(handleRes);
).then(handleAPIv1Res);

expect(headers['x-readme-source-url']).toBe(
'https://github.com/octocat/Hello-World/blob/ffac537e6cbbf934b08745a378932722df287a53/openapi.json',
Expand All @@ -81,14 +81,14 @@ describe('#readmeAPIV1Fetch()', () => {
return this.req.headers;
});

const headers = await readmeAPIV1Fetch(
const headers = await readmeAPIv1Fetch(
'/api/v1',
{
method: 'get',
headers: cleanHeaders(key),
headers: cleanAPIv1Headers(key),
},
{ filePath: './📈 Dashboard & Metrics/openapi.json', fileType: 'path' },
).then(handleRes);
).then(handleAPIv1Res);

expect(headers['x-readme-source-url']).toBe(
'https://github.com/octocat/Hello-World/blob/ffac537e6cbbf934b08745a378932722df287a53/%F0%9F%93%88%20Dashboard%20&%20Metrics/openapi.json',
Expand All @@ -107,14 +107,14 @@ describe('#readmeAPIV1Fetch()', () => {
return this.req.headers;
});

const headers = await readmeAPIV1Fetch(
const headers = await readmeAPIv1Fetch(
'/api/v1',
{
method: 'get',
headers: cleanHeaders(key),
headers: cleanAPIv1Headers(key),
},
{ filePath: './📈 Dashboard & Metrics/openapi.json', fileType: 'path' },
).then(handleRes);
).then(handleAPIv1Res);

expect(headers['x-readme-source-url']).toBeUndefined();
mock.done();
Expand All @@ -130,14 +130,14 @@ describe('#readmeAPIV1Fetch()', () => {
return this.req.headers;
});

const headers = await readmeAPIV1Fetch(
const headers = await readmeAPIv1Fetch(
'/api/v1',
{
method: 'get',
headers: cleanHeaders(key),
headers: cleanAPIv1Headers(key),
},
{ filePath: './openapi.json', fileType: 'path' },
).then(handleRes);
).then(handleAPIv1Res);

expect(headers['x-readme-source-url']).toBe(
'https://github.com/octocat/Hello-World/blob/ffac537e6cbbf934b08745a378932722df287a53/openapi.json',
Expand All @@ -156,14 +156,14 @@ describe('#readmeAPIV1Fetch()', () => {
return this.req.headers;
});

const headers = await readmeAPIV1Fetch(
const headers = await readmeAPIv1Fetch(
'/api/v1',
{
method: 'get',
headers: cleanHeaders(key),
headers: cleanAPIv1Headers(key),
},
{ filePath, fileType: 'url' },
).then(handleRes);
).then(handleAPIv1Res);

expect(headers['x-readme-source-url']).toBe(filePath);
mock.done();
Expand All @@ -181,10 +181,10 @@ describe('#readmeAPIV1Fetch()', () => {
return this.req.headers;
});

const headers = await readmeAPIV1Fetch('/api/v1', {
const headers = await readmeAPIv1Fetch('/api/v1', {
method: 'get',
headers: cleanHeaders(key),
}).then(handleRes);
headers: cleanAPIv1Headers(key),
}).then(handleAPIv1Res);

expect(headers['user-agent']).toBe(`rdme/${pkg.version}`);
expect(headers['x-readme-source']).toBe('cli');
Expand All @@ -203,7 +203,7 @@ describe('#readmeAPIV1Fetch()', () => {
return this.req.headers;
});

const headers = await readmeAPIV1Fetch('/api/v1/doesnt-need-auth').then(handleRes);
const headers = await readmeAPIv1Fetch('/api/v1/doesnt-need-auth').then(handleAPIv1Res);

expect(headers['user-agent']).toBe(`rdme/${pkg.version}`);
expect(headers['x-readme-source']).toBe('cli');
Expand Down Expand Up @@ -235,7 +235,7 @@ describe('#readmeAPIV1Fetch()', () => {
Warning: '',
});

await readmeAPIV1Fetch('/api/v1/some-warning');
await readmeAPIv1Fetch('/api/v1/some-warning');

expect(console.warn).toHaveBeenCalledTimes(0);
expect(getWarningCommandOutput()).toBe('');
Expand All @@ -248,7 +248,7 @@ describe('#readmeAPIV1Fetch()', () => {
Warning: '199 - "some error"',
});

await readmeAPIV1Fetch('/api/v1/some-warning');
await readmeAPIv1Fetch('/api/v1/some-warning');

expect(console.warn).toHaveBeenCalledTimes(1);
expect(getWarningCommandOutput()).toBe('⚠️ ReadMe API Warning: some error');
Expand All @@ -261,7 +261,7 @@ describe('#readmeAPIV1Fetch()', () => {
Warning: '199 - "some error" 199 - "another error"',
});

await readmeAPIV1Fetch('/api/v1/some-warning');
await readmeAPIv1Fetch('/api/v1/some-warning');

expect(console.warn).toHaveBeenCalledTimes(2);
expect(getWarningCommandOutput()).toBe(
Expand All @@ -276,7 +276,7 @@ describe('#readmeAPIV1Fetch()', () => {
Warning: 'some garbage error',
});

await readmeAPIV1Fetch('/api/v1/some-warning');
await readmeAPIv1Fetch('/api/v1/some-warning');

expect(console.warn).toHaveBeenCalledTimes(1);
expect(getWarningCommandOutput()).toBe('⚠️ ReadMe API Warning: some garbage error');
Expand All @@ -302,7 +302,7 @@ describe('#readmeAPIV1Fetch()', () => {

const mock = getAPIV1Mock({}).get('/api/v1/proxy').reply(200);

await readmeAPIV1Fetch('/api/v1/proxy');
await readmeAPIv1Fetch('/api/v1/proxy');

mock.done();
});
Expand All @@ -314,7 +314,7 @@ describe('#readmeAPIV1Fetch()', () => {

const mock = getAPIV1Mock({}).get('/api/v1/proxy').reply(200);

await readmeAPIV1Fetch('/api/v1/proxy');
await readmeAPIv1Fetch('/api/v1/proxy');

mock.done();
});
Expand All @@ -326,27 +326,27 @@ describe('#readmeAPIV1Fetch()', () => {

const mock = getAPIV1Mock({}).get('/api/v1/proxy').reply(200);

await readmeAPIV1Fetch('/api/v1/proxy');
await readmeAPIv1Fetch('/api/v1/proxy');

mock.done();
});
});
});

describe('#cleanHeaders()', () => {
describe('#cleanAPIv1Headers()', () => {
it('should base64-encode key in ReadMe-friendly format', () => {
expect(Array.from(cleanHeaders('test'))).toStrictEqual([['authorization', 'Basic dGVzdDo=']]);
expect(Array.from(cleanAPIv1Headers('test'))).toStrictEqual([['authorization', 'Basic dGVzdDo=']]);
});

it('should filter out undefined headers', () => {
expect(Array.from(cleanHeaders('test', undefined, new Headers({ 'x-something': undefined })))).toStrictEqual([
expect(Array.from(cleanAPIv1Headers('test', undefined, new Headers({ 'x-something': undefined })))).toStrictEqual([
['authorization', 'Basic dGVzdDo='],
]);
});

it('should filter out null headers', () => {
expect(
Array.from(cleanHeaders('test', undefined, new Headers({ 'x-something': '1234', Accept: null }))),
Array.from(cleanAPIv1Headers('test', undefined, new Headers({ 'x-something': '1234', Accept: null }))),
).toStrictEqual([
['authorization', 'Basic dGVzdDo='],
['x-something', '1234'],
Expand All @@ -360,7 +360,7 @@ describe('#cleanHeaders()', () => {
'Content-Type': 'application/json',
});

expect(Array.from(cleanHeaders('test', undefined, headers))).toStrictEqual([
expect(Array.from(cleanAPIv1Headers('test', undefined, headers))).toStrictEqual([
['accept', 'text/plain'],
['authorization', 'Basic dGVzdDo='],
['content-type', 'application/json'],
Expand Down
8 changes: 4 additions & 4 deletions src/commands/categories/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import chalk from 'chalk';
import BaseCommand from '../../lib/baseCommand.js';
import { keyFlag, versionFlag } from '../../lib/flags.js';
import getCategories from '../../lib/getCategories.js';
import { cleanHeaders, handleRes, readmeAPIV1Fetch } from '../../lib/readmeAPIFetch.js';
import { cleanAPIv1Headers, handleAPIv1Res, readmeAPIv1Fetch } from '../../lib/readmeAPIFetch.js';
import { getProjectVersion } from '../../lib/versionSelect.js';

interface Category {
Expand Down Expand Up @@ -57,15 +57,15 @@ export default class CategoriesCreateCommand extends BaseCommand<typeof Categori
}
}

const createdCategory = await readmeAPIV1Fetch('/api/v1/categories', {
const createdCategory = await readmeAPIv1Fetch('/api/v1/categories', {
method: 'post',
headers: cleanHeaders(key, selectedVersion, new Headers({ 'Content-Type': 'application/json' })),
headers: cleanAPIv1Headers(key, selectedVersion, new Headers({ 'Content-Type': 'application/json' })),
body: JSON.stringify({
title,
type: categoryType,
}),
})
.then(handleRes)
.then(handleAPIv1Res)
.then(res => `🌱 successfully created '${res.title}' with a type of '${res.type}' and an id of '${res.id}'`);

return Promise.resolve(chalk.green(createdCategory));
Expand Down
18 changes: 9 additions & 9 deletions src/commands/openapi/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { info, oraOptions, warn } from '../../lib/logger.js';
import prepareOas from '../../lib/prepareOas.js';
import * as promptHandler from '../../lib/prompts.js';
import promptTerminal from '../../lib/promptWrapper.js';
import { cleanHeaders, handleRes, readmeAPIV1Fetch } from '../../lib/readmeAPIFetch.js';
import { cleanAPIv1Headers, handleAPIv1Res, readmeAPIv1Fetch } from '../../lib/readmeAPIFetch.js';
import streamSpecToRegistry from '../../lib/streamSpecToRegistry.js';
import { getProjectVersion } from '../../lib/versionSelect.js';

Expand Down Expand Up @@ -111,7 +111,7 @@ export default class OpenAPICommand extends BaseCommand<typeof OpenAPICommand> {
? `You've successfully uploaded a new ${specType} file to your ReadMe project!`
: `You've successfully updated an existing ${specType} file on your ReadMe project!`;

const body = await handleRes(data, false);
const body = await handleAPIv1Res(data, false);

const output = {
commandType: isUpdate ? 'update' : 'create',
Expand Down Expand Up @@ -147,7 +147,7 @@ export default class OpenAPICommand extends BaseCommand<typeof OpenAPICommand> {
};

const error = (res: Response) => {
return handleRes(res).catch(err => {
return handleAPIv1Res(res).catch(err => {
// If we receive an APIError, no changes needed! Throw it as is.
if (err.name === 'APIError') {
throw err;
Expand Down Expand Up @@ -176,7 +176,7 @@ export default class OpenAPICommand extends BaseCommand<typeof OpenAPICommand> {
const registryUUID = await streamSpecToRegistry(preparedSpec);

const options: RequestInit = {
headers: cleanHeaders(
headers: cleanAPIv1Headers(
key,
selectedVersion,
new Headers({ Accept: 'application/json', 'Content-Type': 'application/json' }),
Expand All @@ -191,7 +191,7 @@ export default class OpenAPICommand extends BaseCommand<typeof OpenAPICommand> {

options.method = 'post';
spinner.start('Creating your API docs in ReadMe...');
return readmeAPIV1Fetch('/api/v1/api-specification', options, {
return readmeAPIv1Fetch('/api/v1/api-specification', options, {
filePath: specPath,
fileType: specFileType,
}).then(res => {
Expand All @@ -212,7 +212,7 @@ export default class OpenAPICommand extends BaseCommand<typeof OpenAPICommand> {
isUpdate = true;
options.method = 'put';
spinner.start('Updating your API docs in ReadMe...');
return readmeAPIV1Fetch(`/api/v1/api-specification/${specId}`, options, {
return readmeAPIv1Fetch(`/api/v1/api-specification/${specId}`, options, {
filePath: specPath,
fileType: specFileType,
}).then(res => {
Expand All @@ -235,9 +235,9 @@ export default class OpenAPICommand extends BaseCommand<typeof OpenAPICommand> {

function getSpecs(url: string) {
if (url) {
return readmeAPIV1Fetch(url, {
return readmeAPIv1Fetch(url, {
method: 'get',
headers: cleanHeaders(key, selectedVersion),
headers: cleanAPIv1Headers(key, selectedVersion),
});
}

Expand All @@ -261,7 +261,7 @@ export default class OpenAPICommand extends BaseCommand<typeof OpenAPICommand> {
this.debug(`total pages: ${totalPages}`);
this.debug(`pagination result: ${JSON.stringify(parsedDocs)}`);

const apiSettingsBody = await handleRes(apiSettings);
const apiSettingsBody = await handleAPIv1Res(apiSettings);
if (!apiSettingsBody.length) return createSpec();

if (update) {
Expand Down
14 changes: 7 additions & 7 deletions src/commands/versions/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import castStringOptToBool from '../../lib/castStringOptToBool.js';
import { baseVersionFlags, keyFlag } from '../../lib/flags.js';
import * as promptHandler from '../../lib/prompts.js';
import promptTerminal from '../../lib/promptWrapper.js';
import { cleanHeaders, handleRes, readmeAPIV1Fetch } from '../../lib/readmeAPIFetch.js';
import { cleanAPIv1Headers, handleAPIv1Res, readmeAPIv1Fetch } from '../../lib/readmeAPIFetch.js';

export default class CreateVersionCommand extends BaseCommand<typeof CreateVersionCommand> {
static description = 'Create a new version for your project.';
Expand Down Expand Up @@ -42,10 +42,10 @@ export default class CreateVersionCommand extends BaseCommand<typeof CreateVersi
}

if (!fork) {
versionList = await readmeAPIV1Fetch('/api/v1/version', {
versionList = await readmeAPIv1Fetch('/api/v1/version', {
method: 'get',
headers: cleanHeaders(key),
}).then(handleRes);
headers: cleanAPIv1Headers(key),
}).then(handleAPIv1Res);
}

prompts.override({
Expand All @@ -68,16 +68,16 @@ export default class CreateVersionCommand extends BaseCommand<typeof CreateVersi
is_stable: promptResponse.is_stable,
};

return readmeAPIV1Fetch('/api/v1/version', {
return readmeAPIv1Fetch('/api/v1/version', {
method: 'post',
headers: cleanHeaders(
headers: cleanAPIv1Headers(
key,
undefined,
new Headers({ Accept: 'application/json', 'Content-Type': 'application/json' }),
),
body: JSON.stringify(body),
})
.then(handleRes)
.then(handleAPIv1Res)
.then(() => {
return Promise.resolve(`Version ${version} created successfully.`);
});
Expand Down
Loading

0 comments on commit e864491

Please sign in to comment.