Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(fetch): readmeAPIFetch, consolidate base URL #742

Merged
merged 2 commits into from
Feb 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion __tests__/helpers/get-api-mock.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import config from 'config';
import nock from 'nock';

import { getUserAgent } from '../../src/lib/fetch';
import { getUserAgent } from '../../src/lib/readmeAPIFetch';

/**
* Nock wrapper that adds required `user-agent` request header
Expand Down
35 changes: 17 additions & 18 deletions __tests__/lib/fetch.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
/* eslint-disable @typescript-eslint/ban-ts-comment, no-console */
import config from 'config';
import { Headers } from 'node-fetch';

import pkg from '../../package.json';
import fetch, { cleanHeaders, handleRes } from '../../src/lib/fetch';
import readmeAPIFetch, { cleanHeaders, handleRes } from '../../src/lib/readmeAPIFetch';
import getAPIMock from '../helpers/get-api-mock';
import { after, before } from '../helpers/setup-gha-env';

Expand All @@ -23,7 +22,7 @@ describe('#fetch()', () => {
return this.req.headers;
});

const headers = await fetch(`${config.get('host')}/api/v1`, {
const headers = await readmeAPIFetch('/api/v1', {
method: 'get',
headers: cleanHeaders(key),
}).then(handleRes);
Expand All @@ -50,8 +49,8 @@ describe('#fetch()', () => {
return this.req.headers;
});

const headers = await fetch(
`${config.get('host')}/api/v1`,
const headers = await readmeAPIFetch(
'/api/v1',
{
method: 'get',
headers: cleanHeaders(key),
Expand All @@ -75,8 +74,8 @@ describe('#fetch()', () => {
return this.req.headers;
});

const headers = await fetch(
`${config.get('host')}/api/v1`,
const headers = await readmeAPIFetch(
'/api/v1',
{
method: 'get',
headers: cleanHeaders(key),
Expand All @@ -101,8 +100,8 @@ describe('#fetch()', () => {
return this.req.headers;
});

const headers = await fetch(
`${config.get('host')}/api/v1`,
const headers = await readmeAPIFetch(
'/api/v1',
{
method: 'get',
headers: cleanHeaders(key),
Expand All @@ -126,7 +125,7 @@ describe('#fetch()', () => {
return this.req.headers;
});

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

const headers = await fetch(`${config.get('host')}/api/v1/doesnt-need-auth`).then(handleRes);
const headers = await readmeAPIFetch('/api/v1/doesnt-need-auth').then(handleRes);

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

await fetch(`${config.get('host')}/api/v1/some-warning`);
await readmeAPIFetch('/api/v1/some-warning');

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

await fetch(`${config.get('host')}/api/v1/some-warning`);
await readmeAPIFetch('/api/v1/some-warning');

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

await fetch(`${config.get('host')}/api/v1/some-warning`);
await readmeAPIFetch('/api/v1/some-warning');

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

await fetch(`${config.get('host')}/api/v1/some-warning`);
await readmeAPIFetch('/api/v1/some-warning');

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

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

await fetch(`${config.get('host')}/api/v1/proxy`);
await readmeAPIFetch('/api/v1/proxy');

expect(mock.isDone()).toBe(true);
});
Expand All @@ -255,7 +254,7 @@ describe('#fetch()', () => {

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

await fetch(`${config.get('host')}/api/v1/proxy`);
await readmeAPIFetch('/api/v1/proxy');

expect(mock.isDone()).toBe(true);
});
Expand All @@ -267,7 +266,7 @@ describe('#fetch()', () => {

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

await fetch(`${config.get('host')}/api/v1/proxy`);
await readmeAPIFetch('/api/v1/proxy');

expect(mock.isDone()).toBe(true);
});
Expand Down
4 changes: 2 additions & 2 deletions src/cmds/categories/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import config from 'config';
import { Headers } from 'node-fetch';

import Command, { CommandCategories } from '../../lib/baseCommand';
import fetch, { cleanHeaders, handleRes } from '../../lib/fetch';
import getCategories from '../../lib/getCategories';
import readmeAPIFetch, { cleanHeaders, handleRes } from '../../lib/readmeAPIFetch';
import { getProjectVersion } from '../../lib/versionSelect';

interface Category {
Expand Down Expand Up @@ -88,7 +88,7 @@ export default class CategoriesCreateCommand extends Command {
);
}
}
return fetch(`${config.get('host')}/api/v1/categories`, {
return readmeAPIFetch('/api/v1/categories', {
method: 'post',
headers: cleanHeaders(
key,
Expand Down
6 changes: 3 additions & 3 deletions src/cmds/docs/edit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import editor from 'editor';
import APIError from '../../lib/apiError';
import Command, { CommandCategories } from '../../lib/baseCommand';
import isHidden from '../../lib/decorators/isHidden';
import fetch, { cleanHeaders, handleRes } from '../../lib/fetch';
import readmeAPIFetch, { cleanHeaders, handleRes } from '../../lib/readmeAPIFetch';
import { getProjectVersion } from '../../lib/versionSelect';

const writeFile = promisify(fs.writeFile);
Expand Down Expand Up @@ -61,7 +61,7 @@ export default class DocsEditCommand extends Command {

const filename = `${slug}.md`;

const existingDoc = await fetch(`${config.get('host')}/api/v1/docs/${slug}`, {
const existingDoc = await readmeAPIFetch(`/api/v1/docs/${slug}`, {
method: 'get',
headers: cleanHeaders(
key,
Expand All @@ -84,7 +84,7 @@ export default class DocsEditCommand extends Command {

Command.debug(`read edited contents of ${filename}, sending to ReadMe`);

return fetch(`${config.get('host')}/api/v1/docs/${slug}`, {
return readmeAPIFetch(`/api/v1/docs/${slug}`, {
method: 'put',
headers: cleanHeaders(
key,
Expand Down
9 changes: 4 additions & 5 deletions src/cmds/openapi/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,17 @@ import type { CommandOptions } from '../../lib/baseCommand';
import type { RequestInit, Response } from 'node-fetch';

import chalk from 'chalk';
import config from 'config';
import { Headers } from 'node-fetch';
import ora from 'ora';
import parse from 'parse-link-header';

import Command, { CommandCategories } from '../../lib/baseCommand';
import createGHA from '../../lib/createGHA';
import fetch, { cleanHeaders, handleRes } from '../../lib/fetch';
import { oraOptions } from '../../lib/logger';
import prepareOas from '../../lib/prepareOas';
import * as promptHandler from '../../lib/prompts';
import promptTerminal from '../../lib/promptWrapper';
import readmeAPIFetch, { cleanHeaders, handleRes } from '../../lib/readmeAPIFetch';
import streamSpecToRegistry from '../../lib/streamSpecToRegistry';
import { getProjectVersion } from '../../lib/versionSelect';

Expand Down Expand Up @@ -237,7 +236,7 @@ export default class OpenAPICommand extends Command {

options.method = 'post';
spinner.start('Creating your API docs in ReadMe...');
return fetch(`${config.get('host')}/api/v1/api-specification`, options, {
return readmeAPIFetch('/api/v1/api-specification', options, {
filePath: specPath,
fileType: specFileType,
}).then(res => {
Expand All @@ -258,7 +257,7 @@ export default class OpenAPICommand extends Command {
isUpdate = true;
options.method = 'put';
spinner.start('Updating your API docs in ReadMe...');
return fetch(`${config.get('host')}/api/v1/api-specification/${specId}`, options, {
return readmeAPIFetch(`/api/v1/api-specification/${specId}`, options, {
filePath: specPath,
fileType: specFileType,
}).then(res => {
Expand All @@ -280,7 +279,7 @@ export default class OpenAPICommand extends Command {
*/

function getSpecs(url: string) {
return fetch(`${config.get('host')}${url}`, {
return readmeAPIFetch(url, {
method: 'get',
headers: cleanHeaders(
key,
Expand Down
6 changes: 3 additions & 3 deletions src/cmds/versions/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import { Headers } from 'node-fetch';
import semver from 'semver';

import Command, { CommandCategories } from '../../lib/baseCommand';
import fetch, { cleanHeaders, handleRes } from '../../lib/fetch';
import * as promptHandler from '../../lib/prompts';
import promptTerminal from '../../lib/promptWrapper';
import readmeAPIFetch, { cleanHeaders, handleRes } from '../../lib/readmeAPIFetch';

export interface Options extends CommonOptions {
fork?: string;
Expand Down Expand Up @@ -60,7 +60,7 @@ export default class CreateVersionCommand extends Command {
}

if (!fork) {
versionList = await fetch(`${config.get('host')}/api/v1/version`, {
versionList = await readmeAPIFetch('/api/v1/version', {
method: 'get',
headers: cleanHeaders(key),
}).then(handleRes);
Expand All @@ -82,7 +82,7 @@ export default class CreateVersionCommand extends Command {
is_hidden: promptResponse.is_stable ? false : !(isPublic === 'true' || promptResponse.is_hidden),
};

return fetch(`${config.get('host')}/api/v1/version`, {
return readmeAPIFetch('/api/v1/version', {
method: 'post',
headers: cleanHeaders(
key,
Expand Down
6 changes: 2 additions & 4 deletions src/cmds/versions/delete.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import type { CommandOptions } from '../../lib/baseCommand';

import config from 'config';

import Command, { CommandCategories } from '../../lib/baseCommand';
import fetch, { cleanHeaders, handleRes } from '../../lib/fetch';
import readmeAPIFetch, { cleanHeaders, handleRes } from '../../lib/readmeAPIFetch';
import { getProjectVersion } from '../../lib/versionSelect';

export default class DeleteVersionCommand extends Command {
Expand Down Expand Up @@ -35,7 +33,7 @@ export default class DeleteVersionCommand extends Command {

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

return fetch(`${config.get('host')}/api/v1/version/${selectedVersion}`, {
return readmeAPIFetch(`/api/v1/version/${selectedVersion}`, {
method: 'delete',
headers: cleanHeaders(key),
})
Expand Down
8 changes: 3 additions & 5 deletions src/cmds/versions/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import type { CommandOptions } from '../../lib/baseCommand';

import config from 'config';

import Command, { CommandCategories } from '../../lib/baseCommand';
import fetch, { cleanHeaders, handleRes } from '../../lib/fetch';
import readmeAPIFetch, { cleanHeaders, handleRes } from '../../lib/readmeAPIFetch';

export interface Version {
codename?: string;
Expand Down Expand Up @@ -40,9 +38,9 @@ export default class VersionsCommand extends Command {

const { key, version } = opts;

const uri = version ? `${config.get('host')}/api/v1/version/${version}` : `${config.get('host')}/api/v1/version`;
const uri = version ? `/api/v1/version/${version}` : '/api/v1/version';

return fetch(uri, {
return readmeAPIFetch(uri, {
method: 'get',
headers: cleanHeaders(key),
})
Expand Down
7 changes: 3 additions & 4 deletions src/cmds/versions/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@ import type { Version } from '.';
import type { CommonOptions } from './create';
import type { CommandOptions } from '../../lib/baseCommand';

import config from 'config';
import { Headers } from 'node-fetch';

import Command, { CommandCategories } from '../../lib/baseCommand';
import fetch, { cleanHeaders, handleRes } from '../../lib/fetch';
import * as promptHandler from '../../lib/prompts';
import promptTerminal from '../../lib/promptWrapper';
import readmeAPIFetch, { cleanHeaders, handleRes } from '../../lib/readmeAPIFetch';
import { getProjectVersion } from '../../lib/versionSelect';

export interface Options extends CommonOptions {
Expand Down Expand Up @@ -56,7 +55,7 @@ export default class UpdateVersionCommand extends Command {

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

const foundVersion = await fetch(`${config.get('host')}/api/v1/version/${selectedVersion}`, {
const foundVersion = await readmeAPIFetch(`/api/v1/version/${selectedVersion}`, {
method: 'get',
headers: cleanHeaders(key),
}).then(handleRes);
Expand All @@ -72,7 +71,7 @@ export default class UpdateVersionCommand extends Command {
is_hidden: promptResponse.is_stable ? false : !(isPublic === 'true' || promptResponse.is_hidden),
};

return fetch(`${config.get('host')}/api/v1/version/${selectedVersion}`, {
return readmeAPIFetch(`/api/v1/version/${selectedVersion}`, {
method: 'put',
headers: cleanHeaders(
key,
Expand Down
5 changes: 2 additions & 3 deletions src/lib/deleteDoc.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import type { CommandCategories } from './baseCommand';

import config from 'config';
import { Headers } from 'node-fetch';

import fetch, { cleanHeaders, handleRes } from './fetch';
import readmeAPIFetch, { cleanHeaders, handleRes } from './readmeAPIFetch';

/**
* Delete a document from ReadMe
Expand All @@ -25,7 +24,7 @@ export default async function deleteDoc(
if (dryRun) {
return Promise.resolve(`🎭 dry run! This will delete \`${slug}\`.`);
}
return fetch(`${config.get('host')}/api/v1/${type}/${slug}`, {
return readmeAPIFetch(`/api/v1/${type}/${slug}`, {
method: 'delete',
headers: cleanHeaders(
key,
Expand Down
7 changes: 3 additions & 4 deletions src/lib/getCategories.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import config from 'config';
import { Headers } from 'node-fetch';

import fetch, { cleanHeaders, handleRes } from './fetch';
import readmeAPIFetch, { cleanHeaders, handleRes } from './readmeAPIFetch';

/**
* Returns all categories for a given project and version
Expand All @@ -13,7 +12,7 @@ import fetch, { cleanHeaders, handleRes } from './fetch';
export default async function getCategories(key: string, selectedVersion: string) {
function getNumberOfPages() {
let totalCount = 0;
return fetch(`${config.get('host')}/api/v1/categories?perPage=20&page=1`, {
return readmeAPIFetch('/api/v1/categories?perPage=20&page=1', {
method: 'get',
headers: cleanHeaders(
key,
Expand All @@ -38,7 +37,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 fetch(`${config.get('host')}/api/v1/categories?perPage=20&page=${page}`, {
return readmeAPIFetch(`/api/v1/categories?perPage=20&page=${page}`, {
method: 'get',
headers: cleanHeaders(
key,
Expand Down
Loading