Skip to content

Commit

Permalink
refactor(fetch): use named function, add v1
Browse files Browse the repository at this point in the history
  • Loading branch information
kanadgupta committed Nov 19, 2024
1 parent 29d5906 commit 7c0cdc9
Show file tree
Hide file tree
Showing 15 changed files with 52 additions and 52 deletions.
34 changes: 17 additions & 17 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 readmeAPIFetch, { cleanHeaders, handleRes } from '../../src/lib/readmeAPIFetch.js';
import { cleanHeaders, handleRes, readmeAPIV1Fetch } from '../../src/lib/readmeAPIFetch.js';
import getAPIMock from '../helpers/get-api-mock.js';
import { after, before } from '../helpers/setup-gha-env.js';

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

const headers = await readmeAPIFetch('/api/v1', {
const headers = await readmeAPIV1Fetch('/api/v1', {
method: 'get',
headers: cleanHeaders(key),
}).then(handleRes);
Expand All @@ -56,7 +56,7 @@ describe('#fetch()', () => {
return this.req.headers;
});

const headers = await readmeAPIFetch(
const headers = await readmeAPIV1Fetch(
'/api/v1',
{
method: 'get',
Expand All @@ -81,7 +81,7 @@ describe('#fetch()', () => {
return this.req.headers;
});

const headers = await readmeAPIFetch(
const headers = await readmeAPIV1Fetch(
'/api/v1',
{
method: 'get',
Expand All @@ -107,7 +107,7 @@ describe('#fetch()', () => {
return this.req.headers;
});

const headers = await readmeAPIFetch(
const headers = await readmeAPIV1Fetch(
'/api/v1',
{
method: 'get',
Expand All @@ -130,7 +130,7 @@ describe('#fetch()', () => {
return this.req.headers;
});

const headers = await readmeAPIFetch(
const headers = await readmeAPIV1Fetch(
'/api/v1',
{
method: 'get',
Expand All @@ -156,7 +156,7 @@ describe('#fetch()', () => {
return this.req.headers;
});

const headers = await readmeAPIFetch(
const headers = await readmeAPIV1Fetch(
'/api/v1',
{
method: 'get',
Expand All @@ -181,7 +181,7 @@ describe('#fetch()', () => {
return this.req.headers;
});

const headers = await readmeAPIFetch('/api/v1', {
const headers = await readmeAPIV1Fetch('/api/v1', {
method: 'get',
headers: cleanHeaders(key),
}).then(handleRes);
Expand All @@ -203,7 +203,7 @@ describe('#fetch()', () => {
return this.req.headers;
});

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

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

await readmeAPIFetch('/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('#fetch()', () => {
Warning: '199 - "some error"',
});

await readmeAPIFetch('/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('#fetch()', () => {
Warning: '199 - "some error" 199 - "another error"',
});

await readmeAPIFetch('/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('#fetch()', () => {
Warning: 'some garbage error',
});

await readmeAPIFetch('/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('#fetch()', () => {

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

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

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

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

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

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

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

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

mock.done();
});
Expand Down
4 changes: 2 additions & 2 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 readmeAPIFetch, { cleanHeaders, handleRes } from '../../lib/readmeAPIFetch.js';
import { cleanHeaders, handleRes, readmeAPIV1Fetch } from '../../lib/readmeAPIFetch.js';
import { getProjectVersion } from '../../lib/versionSelect.js';

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

const createdCategory = await readmeAPIFetch('/api/v1/categories', {
const createdCategory = await readmeAPIV1Fetch('/api/v1/categories', {
method: 'post',
headers: cleanHeaders(key, selectedVersion, new Headers({ 'Content-Type': 'application/json' })),
body: JSON.stringify({
Expand Down
8 changes: 4 additions & 4 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 readmeAPIFetch, { cleanHeaders, handleRes } from '../../lib/readmeAPIFetch.js';
import { cleanHeaders, handleRes, readmeAPIV1Fetch } from '../../lib/readmeAPIFetch.js';
import streamSpecToRegistry from '../../lib/streamSpecToRegistry.js';
import { getProjectVersion } from '../../lib/versionSelect.js';

Expand Down Expand Up @@ -193,7 +193,7 @@ export default class OpenAPICommand extends BaseCommand<typeof OpenAPICommand> {

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

function getSpecs(url: string) {
if (url) {
return readmeAPIFetch(url, {
return readmeAPIV1Fetch(url, {
method: 'get',
headers: cleanHeaders(key, selectedVersion),
});
Expand Down
6 changes: 3 additions & 3 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 readmeAPIFetch, { cleanHeaders, handleRes } from '../../lib/readmeAPIFetch.js';
import { cleanHeaders, handleRes, 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,7 +42,7 @@ export default class CreateVersionCommand extends BaseCommand<typeof CreateVersi
}

if (!fork) {
versionList = await readmeAPIFetch('/api/v1/version', {
versionList = await readmeAPIV1Fetch('/api/v1/version', {
method: 'get',
headers: cleanHeaders(key),
}).then(handleRes);
Expand All @@ -68,7 +68,7 @@ export default class CreateVersionCommand extends BaseCommand<typeof CreateVersi
is_stable: promptResponse.is_stable,
};

return readmeAPIFetch('/api/v1/version', {
return readmeAPIV1Fetch('/api/v1/version', {
method: 'post',
headers: cleanHeaders(
key,
Expand Down
4 changes: 2 additions & 2 deletions src/commands/versions/delete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Args } from '@oclif/core';

import BaseCommand from '../../lib/baseCommand.js';
import { keyFlag } from '../../lib/flags.js';
import readmeAPIFetch, { cleanHeaders, handleRes } from '../../lib/readmeAPIFetch.js';
import { cleanHeaders, handleRes, readmeAPIV1Fetch } from '../../lib/readmeAPIFetch.js';
import { getProjectVersion } from '../../lib/versionSelect.js';

export default class DeleteVersionCommand extends BaseCommand<typeof DeleteVersionCommand> {
Expand All @@ -26,7 +26,7 @@ export default class DeleteVersionCommand extends BaseCommand<typeof DeleteVersi

this.debug(`selectedVersion: ${selectedVersion}`);

return readmeAPIFetch(`/api/v1/version/${selectedVersion}`, {
return readmeAPIV1Fetch(`/api/v1/version/${selectedVersion}`, {
method: 'delete',
headers: cleanHeaders(key),
})
Expand Down
4 changes: 2 additions & 2 deletions src/commands/versions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Flags } from '@oclif/core';

import BaseCommand from '../../lib/baseCommand.js';
import { keyFlag } from '../../lib/flags.js';
import readmeAPIFetch, { cleanHeaders, handleRes } from '../../lib/readmeAPIFetch.js';
import { cleanHeaders, handleRes, readmeAPIV1Fetch } from '../../lib/readmeAPIFetch.js';

export interface Version {
codename?: string;
Expand All @@ -28,7 +28,7 @@ export default class VersionsCommand extends BaseCommand<typeof VersionsCommand>

const uri = version ? `/api/v1/version/${version}` : '/api/v1/version';

return readmeAPIFetch(uri, {
return readmeAPIV1Fetch(uri, {
method: 'get',
headers: cleanHeaders(key),
})
Expand Down
6 changes: 3 additions & 3 deletions src/commands/versions/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,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 readmeAPIFetch, { cleanHeaders, handleRes } from '../../lib/readmeAPIFetch.js';
import { cleanHeaders, handleRes, readmeAPIV1Fetch } from '../../lib/readmeAPIFetch.js';
import { getProjectVersion } from '../../lib/versionSelect.js';

export default class UpdateVersionCommand extends BaseCommand<typeof UpdateVersionCommand> {
Expand All @@ -34,7 +34,7 @@ export default class UpdateVersionCommand extends BaseCommand<typeof UpdateVersi

// TODO: I think this fetch here is unnecessary but
// it will require a bigger refactor of getProjectVersion
const foundVersion: Version = await readmeAPIFetch(`/api/v1/version/${selectedVersion}`, {
const foundVersion: Version = await readmeAPIV1Fetch(`/api/v1/version/${selectedVersion}`, {
method: 'get',
headers: cleanHeaders(key),
}).then(handleRes);
Expand All @@ -59,7 +59,7 @@ export default class UpdateVersionCommand extends BaseCommand<typeof UpdateVersi
is_stable: promptResponse.is_stable,
};

return readmeAPIFetch(`/api/v1/version/${selectedVersion}`, {
return readmeAPIV1Fetch(`/api/v1/version/${selectedVersion}`, {
method: 'put',
headers: cleanHeaders(
key,
Expand Down
4 changes: 2 additions & 2 deletions src/lib/deleteDoc.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import readmeAPIFetch, { cleanHeaders, handleRes } from './readmeAPIFetch.js';
import { cleanHeaders, handleRes, readmeAPIV1Fetch } from './readmeAPIFetch.js';

/**
* Delete a document from ReadMe
Expand All @@ -19,7 +19,7 @@ export default async function deleteDoc(
if (dryRun) {
return Promise.resolve(`🎭 dry run! This will delete \`${slug}\`.`);
}
return readmeAPIFetch(`/api/v1/docs/${slug}`, {
return readmeAPIV1Fetch(`/api/v1/docs/${slug}`, {
method: 'delete',
headers: cleanHeaders(key, selectedVersion, new Headers({ 'Content-Type': 'application/json' })),
})
Expand Down
6 changes: 3 additions & 3 deletions src/lib/getCategories.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import readmeAPIFetch, { cleanHeaders, handleRes } from './readmeAPIFetch.js';
import { cleanHeaders, handleRes, readmeAPIV1Fetch } from './readmeAPIFetch.js';

/**
* Returns all categories for a given project and version
Expand All @@ -10,7 +10,7 @@ import readmeAPIFetch, { cleanHeaders, handleRes } from './readmeAPIFetch.js';
export default async function getCategories(key: string, selectedVersion: string | undefined) {
async function getNumberOfPages() {
let totalCount = 0;
return readmeAPIFetch('/api/v1/categories?perPage=20&page=1', {
return readmeAPIV1Fetch('/api/v1/categories?perPage=20&page=1', {
method: 'get',
headers: cleanHeaders(key, selectedVersion, new Headers({ Accept: 'application/json' })),
})
Expand All @@ -29,7 +29,7 @@ export default async function getCategories(key: string, selectedVersion: string
...(await Promise.all(
// retrieves all categories beyond first page
[...new Array(totalCount + 1).keys()].slice(2).map(async page => {
return readmeAPIFetch(`/api/v1/categories?perPage=20&page=${page}`, {
return readmeAPIV1Fetch(`/api/v1/categories?perPage=20&page=${page}`, {
method: 'get',
headers: cleanHeaders(key, selectedVersion, new Headers({ Accept: 'application/json' })),
}).then(handleRes);
Expand Down
4 changes: 2 additions & 2 deletions src/lib/getDocs.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import getCategories from './getCategories.js';
import readmeAPIFetch, { cleanHeaders, handleRes } from './readmeAPIFetch.js';
import { cleanHeaders, handleRes, readmeAPIV1Fetch } from './readmeAPIFetch.js';

interface Document {
_id: string;
Expand Down Expand Up @@ -34,7 +34,7 @@ async function getCategoryDocs(
selectedVersion: string | undefined,
category: string,
): Promise<Document[]> {
return readmeAPIFetch(`/api/v1/categories/${category}/docs`, {
return readmeAPIV1Fetch(`/api/v1/categories/${category}/docs`, {
method: 'get',
headers: cleanHeaders(key, selectedVersion, new Headers({ 'Content-Type': 'application/json' })),
}).then(handleRes);
Expand Down
4 changes: 2 additions & 2 deletions src/lib/loginFlow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import configStore from './configstore.js';
import getCurrentConfig from './getCurrentConfig.js';
import { debug } from './logger.js';
import promptTerminal from './promptWrapper.js';
import readmeAPIFetch, { handleRes } from './readmeAPIFetch.js';
import { handleRes, readmeAPIV1Fetch } from './readmeAPIFetch.js';
import { validateSubdomain } from './validatePromptInput.js';

interface LoginBody {
Expand All @@ -16,7 +16,7 @@ interface LoginBody {
}

function loginFetch(body: LoginBody) {
return readmeAPIFetch('/api/v1/login', {
return readmeAPIV1Fetch('/api/v1/login', {
method: 'post',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify(body),
Expand Down
2 changes: 1 addition & 1 deletion src/lib/readmeAPIFetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ function sanitizeHeaders(headers: Headers) {
* @param fileOpts optional object containing information about the file being sent.
* We use this to construct a full source URL for the file.
*/
export default async function readmeAPIFetch(
export async function readmeAPIV1Fetch(
pathname: string,
options: RequestInit = { headers: new Headers() },
fileOpts: FilePathDetails = { filePath: '', fileType: false },
Expand Down
4 changes: 2 additions & 2 deletions src/lib/streamSpecToRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import ora from 'ora';
import { file as tmpFile } from 'tmp-promise';

import { debug, oraOptions } from './logger.js';
import readmeAPIFetch, { handleRes } from './readmeAPIFetch.js';
import { handleRes, readmeAPIV1Fetch } from './readmeAPIFetch.js';

/**
* Uploads a spec to the API registry for usage in ReadMe
Expand Down Expand Up @@ -40,7 +40,7 @@ export default async function streamSpecToRegistry(spec: string) {
method: 'POST',
};

return readmeAPIFetch('/api/v1/api-registry', options)
return readmeAPIV1Fetch('/api/v1/api-registry', options)
.then(handleRes)
.then(body => {
spinner.stop();
Expand Down
Loading

0 comments on commit 7c0cdc9

Please sign in to comment.